"""
Sheet-targeted webhook subscription models.
"""

from __future__ import annotations

from datetime import datetime, timezone
import uuid
from typing import Any, Dict, Optional

from sqlalchemy import (
    Boolean,
    Column,
    DateTime,
    ForeignKey,
    Index,
    Integer,
    JSON,
    String,
    Text,
)
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlmodel import Field

from fmatch.saas.db import Base


def _utcnow() -> datetime:
    return datetime.now(timezone.utc).replace(tzinfo=None)


class SheetWebhookSubscription(Base, table=True):
    """Binds a webhook secret to a destination spreadsheet + tab."""

    __tablename__ = "sheet_webhook_subscriptions"

    id: uuid.UUID = Field(
        default_factory=uuid.uuid4,
        sa_column=Column(PG_UUID(as_uuid=True), primary_key=True),
    )
    account_id: str = Field(
        sa_column=Column(String(36), ForeignKey("accounts.id"), nullable=False)
    )
    name: str = Field(sa_column=Column(String(255), nullable=False))
    spreadsheet_id: str = Field(sa_column=Column(String(255), nullable=False))
    sheet_name: str = Field(sa_column=Column(String(255), nullable=False))
    create_sheet: bool = Field(
        default=False,
        sa_column=Column(Boolean, nullable=False, default=False),
    )
    write_mode: str = Field(
        default="append",
        sa_column=Column(String(32), nullable=False, default="append"),
    )
    secret: str = Field(sa_column=Column(String(64), nullable=False))
    active: bool = Field(
        default=True,
        sa_column=Column(Boolean, nullable=False, default=True),
    )

    # Delivery stats and debugging
    last_received_at: Optional[datetime] = Field(
        default=None,
        sa_column=Column(DateTime),
    )
    total_deliveries: int = Field(
        default=0,
        sa_column=Column(Integer, nullable=False, default=0),
    )
    total_rows_written: int = Field(
        default=0,
        sa_column=Column(Integer, nullable=False, default=0),
    )
    last_error: Optional[str] = Field(default=None, sa_column=Column(Text))
    last_payload: Optional[Dict[str, Any]] = Field(
        default=None,
        sa_column=Column(JSON),
    )

    created_at: datetime = Field(
        default_factory=_utcnow,
        sa_column=Column(DateTime, nullable=False),
    )
    updated_at: datetime = Field(
        default_factory=_utcnow,
        sa_column=Column(DateTime, nullable=False),
    )

    __table_args__ = (
        Index(
            "idx_sheet_webhook_subscriptions_account_active",
            "account_id",
            "active",
        ),
        Index(
            "idx_sheet_webhook_subscriptions_secret",
            "secret",
            unique=True,
        ),
        Index(
            "idx_sheet_webhook_subscriptions_account_sheet",
            "account_id",
            "spreadsheet_id",
        ),
        {"extend_existing": True},
    )
