"""Bootstrap models for newly provisioned tenant databases.

These tables are intentionally minimal and separate from the existing app
schemas. They provide a stable starting point for tenant-specific metadata and
usage tracking without modifying any code under ``/apps``.
"""

from __future__ import annotations

import uuid
from datetime import datetime

from sqlalchemy import Boolean, DateTime, JSON, String, Text
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column


def _uuid() -> str:
    return str(uuid.uuid4())


class TenantBootstrapBase(DeclarativeBase):
    """Base for per-tenant bootstrap tables."""


class TenantUser(TenantBootstrapBase):
    """Minimal tenant-scoped user record created during provisioning."""

    __tablename__ = "users"

    user_id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
    email: Mapped[str] = mapped_column(String(255), unique=True, nullable=False, index=True)
    role: Mapped[str] = mapped_column(String(32), nullable=False, default="admin")
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)


class TenantUsageRecord(TenantBootstrapBase):
    """Minimal usage table available from day one for every tenant DB."""

    __tablename__ = "usage"

    usage_id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
    metric_name: Mapped[str] = mapped_column(String(128), nullable=False)
    metric_value: Mapped[str] = mapped_column(String(64), nullable=False, default="0")
    metadata_json: Mapped[dict | None] = mapped_column("metadata", JSON, nullable=True)
    recorded_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)


class TenantAppConfig(TenantBootstrapBase):
    """Key-value config store for default tenant app settings."""

    __tablename__ = "app_config"

    config_key: Mapped[str] = mapped_column(String(128), primary_key=True)
    config_value: Mapped[str | None] = mapped_column(Text, nullable=True)
    config_json: Mapped[dict | None] = mapped_column("config", JSON, nullable=True)
    updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
