"""Tenant + TenantSession (JWT revocation) ORM tanımları. Sadece tablo şeması."""
from datetime import datetime

from sqlalchemy import (
    DECIMAL,
    Boolean,
    DateTime,
    Enum,
    ForeignKey,
    Integer,
    String,
    func,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.database import Base, TimestampMixin, UUIDMixin

PLAN_VALUES = ("free", "starter", "pro", "business")


class Tenant(UUIDMixin, TimestampMixin, Base):
    __tablename__ = "tenants"

    name: Mapped[str] = mapped_column(String(200), nullable=False)
    email: Mapped[str] = mapped_column(String(200), nullable=False, unique=True)
    password_hash: Mapped[str] = mapped_column(String(255), nullable=False)

    plan: Mapped[str] = mapped_column(
        Enum(*PLAN_VALUES, name="tenant_plan"), default="free", server_default="free"
    )
    plan_expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default="1")

    api_key: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
    webhook_secret: Mapped[str] = mapped_column(String(64), nullable=False)

    monthly_message_quota: Mapped[int] = mapped_column(
        Integer, default=100, server_default="100"
    )
    monthly_message_used: Mapped[int] = mapped_column(
        Integer, default=0, server_default="0"
    )
    ai_budget_monthly: Mapped[float] = mapped_column(
        DECIMAL(10, 2), default=0, server_default="0"
    )
    ai_budget_used: Mapped[float] = mapped_column(
        DECIMAL(10, 2), default=0, server_default="0"
    )
    ai_budget_period: Mapped[str | None] = mapped_column(String(7), nullable=True)

    sessions: Mapped[list["TenantSession"]] = relationship(
        back_populates="tenant", cascade="all, delete-orphan"
    )


class TenantSession(UUIDMixin, Base):
    """JWT revocation — her login bir jti üretir, logout'ta revoked_at işaretlenir."""

    __tablename__ = "tenant_sessions"

    tenant_id: Mapped[str] = mapped_column(
        String(36), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False
    )
    jti: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
    user_agent: Mapped[str | None] = mapped_column(String(255), nullable=True)
    ip_address: Mapped[str | None] = mapped_column(String(45), nullable=True)
    expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
    revoked_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )

    tenant: Mapped["Tenant"] = relationship(back_populates="sessions")
