from datetime import datetime
from typing import Optional, TYPE_CHECKING

from sqlalchemy import Index, String, Text, DateTime
from sqlalchemy.dialects.postgresql import INET
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.database.base import BaseModel

if TYPE_CHECKING:
    from src.apps.site_admin.models.enquiry_audit_log import EnquiryAuditLog


class WebsiteEnquiry(BaseModel):
    """Platform-level contact/enquiry leads from the marketing site. Not tenant-scoped."""

    __tablename__ = "website_enquiries"

    name: Mapped[str] = mapped_column(String(255), nullable=False)
    email: Mapped[str] = mapped_column(String(255), nullable=False)
    organization: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    cemetery_type: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
    message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    status: Mapped[str] = mapped_column(String(50), nullable=False, default="new", server_default="new")
    source: Mapped[str] = mapped_column(String(100), nullable=False, default="marketing", server_default="marketing")
    ip_address: Mapped[Optional[str]] = mapped_column(INET, nullable=True)
    user_agent: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    type: Mapped[str] = mapped_column(String(20), nullable=False, default="contact", server_default="contact")
    role: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
    phone: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
    day: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
    time: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)

    # INDL-06: workflow timestamp columns
    contacted_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
    contact_method: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
    qualified_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
    qualified_email_sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
    signup_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
    auto_closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)

    audit_logs: Mapped[list["EnquiryAuditLog"]] = relationship(
        "EnquiryAuditLog", back_populates="enquiry", order_by="EnquiryAuditLog.created_at"
    )

    __table_args__ = (
        Index("ix_website_enquiries_status", "status"),
        Index("ix_website_enquiries_email", "email"),
        Index("ix_website_enquiries_created_at", "created_at"),
        Index("ix_website_enquiries_type", "type"),
    )
