import uuid
from datetime import datetime, timezone

from sqlalchemy import DateTime, String, Text, func
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column

from src.core.db import Base


class GroupConfig(Base):
    """Stores per-Google-Group Campflow credentials (encrypted) and metadata."""

    __tablename__ = "group_configs"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )

    # The Google Group email address (unique identifier for the group)
    group_email: Mapped[str] = mapped_column(String(255), unique=True, index=True)

    # Google Workspace admin email used for service-account impersonation
    google_admin_email: Mapped[str | None] = mapped_column(String(255), nullable=True)

    # Fernet-encrypted Campflow API bearer token
    campflow_api_token_enc: Mapped[str | None] = mapped_column(Text, nullable=True)

    # Fernet-encrypted full service-account JSON (stored as string, not a file path)
    service_account_json_enc: Mapped[str | None] = mapped_column(Text, nullable=True)

    # Mailing settings
    email_account: Mapped[str | None] = mapped_column(String(255), nullable=True)
    email_password_enc: Mapped[str | None] = mapped_column(Text, nullable=True)
    pdf_filename: Mapped[str | None] = mapped_column(String(255), nullable=True)

    # Server settings
    imap_server: Mapped[str | None] = mapped_column(String(255), nullable=True)
    imap_port: Mapped[int | None] = mapped_column(nullable=True)
    smtp_server: Mapped[str | None] = mapped_column(String(255), nullable=True)
    smtp_port: Mapped[int | None] = mapped_column(nullable=True)

    # Automation
    auto_mail_recipient: Mapped[str | None] = mapped_column(String(255), nullable=True)

    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(),
        onupdate=lambda: datetime.now(timezone.utc),
    )

class LogEntry(Base):
    """Tracks user actions for audit and transparency (e.g. data access)."""

    __tablename__ = "audit_logs"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )

    # Scoped to a group
    group_email: Mapped[str] = mapped_column(String(255), index=True)

    # Who did it
    user_email: Mapped[str] = mapped_column(String(255), index=True)

    # Action type (e.g. VIEW_EVENT, DOWNLOAD_PDF, SEND_MAIL, UPDATE_SETTINGS)
    action: Mapped[str] = mapped_column(String(50))

    # Optional extra info (e.g. event name, filename)
    details: Mapped[str | None] = mapped_column(Text, nullable=True)

    timestamp: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(),
    )
