# @File: backend/schemas/whatsapp_admin.py
# @Desc: Pydantic schemas for the WhatsApp Reseller Manager admin console.
#        Mirrors the shape of schemas/bizmail.py so the frontend can reuse
#        the same list/card/detail patterns.
from __future__ import annotations

from datetime import datetime
from typing import List, Optional

from pydantic import BaseModel, ConfigDict, Field


class WhatsappPackageBase(BaseModel):
    slug: str = Field(..., min_length=2, max_length=64)
    name: str = Field(..., min_length=1, max_length=128)
    description: Optional[str] = None
    tagline: Optional[str] = None

    max_devices: int = 1
    devices_unlimited: bool = False
    messages_per_month: int = 1000
    messages_unlimited: bool = False
    max_contacts: int = 1000
    contacts_unlimited: bool = False
    max_campaigns: int = 5
    campaigns_unlimited: bool = False
    max_workflows: int = 5
    workflows_unlimited: bool = False
    max_team_operators: int = 1
    team_operators_unlimited: bool = False
    chat_retention_days: int = 90

    auto_reply_allowed: bool = False
    ai_assistant_allowed: bool = False
    workflow_automation_allowed: bool = False
    webhook_access_allowed: bool = False
    api_access_allowed: bool = False
    media_sending_allowed: bool = True
    template_messages_allowed: bool = False

    whmcs_product_id: Optional[int] = None
    terminate_action: str = "archive"  # archive | delete

    is_active: bool = True
    is_featured: bool = False
    price_per_month: Optional[str] = None
    sort_order: int = 0


class WhatsappPackageCreate(WhatsappPackageBase):
    pass


class WhatsappPackageUpdate(BaseModel):
    # every field optional for PATCH-style updates
    slug: Optional[str] = None
    name: Optional[str] = None
    description: Optional[str] = None
    tagline: Optional[str] = None

    max_devices: Optional[int] = None
    devices_unlimited: Optional[bool] = None
    messages_per_month: Optional[int] = None
    messages_unlimited: Optional[bool] = None
    max_contacts: Optional[int] = None
    contacts_unlimited: Optional[bool] = None
    max_campaigns: Optional[int] = None
    campaigns_unlimited: Optional[bool] = None
    max_workflows: Optional[int] = None
    workflows_unlimited: Optional[bool] = None
    max_team_operators: Optional[int] = None
    team_operators_unlimited: Optional[bool] = None
    chat_retention_days: Optional[int] = None

    auto_reply_allowed: Optional[bool] = None
    ai_assistant_allowed: Optional[bool] = None
    workflow_automation_allowed: Optional[bool] = None
    webhook_access_allowed: Optional[bool] = None
    api_access_allowed: Optional[bool] = None
    media_sending_allowed: Optional[bool] = None
    template_messages_allowed: Optional[bool] = None

    whmcs_product_id: Optional[int] = None
    terminate_action: Optional[str] = None

    is_active: Optional[bool] = None
    is_featured: Optional[bool] = None
    price_per_month: Optional[str] = None
    sort_order: Optional[int] = None


class WhatsappPackageOut(WhatsappPackageBase):
    model_config = ConfigDict(from_attributes=True)

    id: int
    created_at: datetime
    updated_at: datetime


class WhatsappSubscriptionOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: int
    user_id: str
    user_email: Optional[str] = None
    package_id: int
    whmcs_service_id: Optional[int] = None
    whmcs_product_id: Optional[int] = None
    status: str

    devices_used: int = 0
    messages_used_month: int = 0
    contacts_used: int = 0
    campaigns_used: int = 0
    workflows_used: int = 0
    usage_period_start: Optional[datetime] = None

    notes: Optional[str] = None
    activated_at: Optional[datetime] = None
    suspended_at: Optional[datetime] = None
    terminated_at: Optional[datetime] = None

    created_at: datetime
    updated_at: datetime


class WhatsappSubscriptionDetail(WhatsappSubscriptionOut):
    """Subscription payload enriched with its package summary."""

    package: Optional[WhatsappPackageOut] = None


class WhatsappSubscriptionActionResult(BaseModel):
    subscription: WhatsappSubscriptionDetail
    message: str


class WhatsappAuditLogOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: int
    actor_user_id: Optional[str] = None
    actor_email: Optional[str] = None
    action: str
    target_type: Optional[str] = None
    target_id: Optional[str] = None
    detail: Optional[str] = None
    created_at: datetime


class WhatsappApiLogOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: int
    subscription_id: Optional[int] = None
    user_id: Optional[str] = None
    channel: str
    method: str
    endpoint: str
    status_code: Optional[int] = None
    duration_ms: Optional[int] = None
    error_detail: Optional[str] = None
    created_at: datetime


class WhatsappIntegrationTestResult(BaseModel):
    ok: bool
    message: str
    latency_ms: Optional[int] = None
    upstream_base_url: Optional[str] = None


class WhatsappAdminOverview(BaseModel):
    total_packages: int
    active_packages: int
    total_subscriptions: int
    active_subscriptions: int
    suspended_subscriptions: int
    terminated_subscriptions: int
    total_devices: int
    connected_devices: int
    messages_last_24h: int

    recent_audit: List[WhatsappAuditLogOut] = []