# backend/app/plugins/contact_forms/models.py
from sqlalchemy import BigInteger, Boolean, ForeignKey, Index, String, Text, Integer, JSON
from sqlalchemy.dialects.mysql import DATETIME as MYSQL_DATETIME, TINYINT
from sqlalchemy.orm import Mapped, mapped_column
from datetime import datetime

from app.core.models.base import Base, TimestampMixin, TenantMixin


class ContactForm(Base, TenantMixin, TimestampMixin):
    __tablename__ = "contact_forms"
    __table_args__ = (
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    name: Mapped[str] = mapped_column(String(100), nullable=False, comment="内部名称")
    title: Mapped[str] = mapped_column(String(200), nullable=False, default="", comment="前端显示标题")
    success_message: Mapped[str] = mapped_column(Text, nullable=False, default="感谢您的提交，我们将尽快回复。")
    notification_emails: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
    admin_email_subject: Mapped[str] = mapped_column(String(500), nullable=False, default="新表单提交：{{form_title}}")
    admin_email_body: Mapped[str] = mapped_column(Text, nullable=False, default="")
    confirm_email_enabled: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=0)
    confirm_email_subject: Mapped[str] = mapped_column(String(500), nullable=False, default="感谢您的提交")
    confirm_email_body: Mapped[str] = mapped_column(Text, nullable=False, default="")
    is_active: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=1)

    def __init__(self, **kwargs):
        kwargs.setdefault("title", "")
        kwargs.setdefault("success_message", "感谢您的提交，我们将尽快回复。")
        kwargs.setdefault("notification_emails", [])
        kwargs.setdefault("admin_email_subject", "新表单提交：{{form_title}}")
        kwargs.setdefault("admin_email_body", "")
        kwargs.setdefault("confirm_email_enabled", 0)
        kwargs.setdefault("confirm_email_subject", "感谢您的提交")
        kwargs.setdefault("confirm_email_body", "")
        kwargs.setdefault("is_active", 1)
        super().__init__(**kwargs)

    def __repr__(self) -> str:
        return f"<ContactForm id={self.id} name={self.name!r}>"


class ContactFormField(Base, TimestampMixin):
    __tablename__ = "contact_form_fields"
    __table_args__ = (
        Index("ix_contact_form_fields_form", "form_id"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    form_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("contact_forms.id", ondelete="CASCADE"), nullable=False
    )
    field_type: Mapped[str] = mapped_column(
        String(20), nullable=False,
        comment="text/textarea/email/tel/number/date/select/radio/checkbox/file/rating/address/hidden"
    )
    label: Mapped[str] = mapped_column(String(200), nullable=False, default="")
    name: Mapped[str] = mapped_column(String(100), nullable=False, comment="变量名，用于邮件模板 {{name}}")
    placeholder: Mapped[str] = mapped_column(String(300), nullable=False, default="")
    is_required: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=0)
    options: Mapped[list] = mapped_column(JSON, nullable=False, default=list, comment='[{"label":"..","value":".."}]')
    sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    validation: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict, comment='{"min":0,"max":100}')

    def __init__(self, **kwargs):
        kwargs.setdefault("label", "")
        kwargs.setdefault("placeholder", "")
        kwargs.setdefault("is_required", 0)
        kwargs.setdefault("options", [])
        kwargs.setdefault("sort_order", 0)
        kwargs.setdefault("validation", {})
        super().__init__(**kwargs)

    def __repr__(self) -> str:
        return f"<ContactFormField id={self.id} form_id={self.form_id} type={self.field_type!r}>"


class ContactFormSubmission(Base, TenantMixin):
    __tablename__ = "contact_form_submissions"
    __table_args__ = (
        Index("ix_cf_submissions_form", "form_id"),
        Index("ix_cf_submissions_tenant_status", "tenant_id", "status"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    form_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("contact_forms.id", ondelete="CASCADE"), nullable=False
    )
    data: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict, comment="提交时字段快照")
    submitter_email: Mapped[str | None] = mapped_column(String(300), nullable=True)
    submitter_name: Mapped[str | None] = mapped_column(String(200), nullable=True)
    status: Mapped[str] = mapped_column(String(20), nullable=False, default="unread", comment="unread/read/replied")
    ip_address: Mapped[str | None] = mapped_column(String(50), nullable=True)
    created_at: Mapped[datetime] = mapped_column(
        MYSQL_DATETIME(fsp=3), nullable=False, default=datetime.utcnow
    )

    def __init__(self, **kwargs):
        kwargs.setdefault("data", {})
        kwargs.setdefault("status", "unread")
        super().__init__(**kwargs)

    def __repr__(self) -> str:
        return f"<ContactFormSubmission id={self.id} form_id={self.form_id} status={self.status!r}>"


class ContactFormReply(Base):
    __tablename__ = "contact_form_replies"
    __table_args__ = (
        Index("ix_cf_replies_submission", "submission_id"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    submission_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("contact_form_submissions.id", ondelete="CASCADE"), nullable=False
    )
    admin_user_id: Mapped[int | None] = mapped_column(
        BigInteger, ForeignKey("users.id", ondelete="SET NULL"), nullable=True
    )
    body: Mapped[str] = mapped_column(Text, nullable=False)
    sent_at: Mapped[datetime] = mapped_column(
        MYSQL_DATETIME(fsp=3), nullable=False, default=datetime.utcnow
    )

    def __repr__(self) -> str:
        return f"<ContactFormReply id={self.id} submission_id={self.submission_id}>"
