"""Shopify App domain - request/response schemas."""
from __future__ import annotations

from datetime import datetime
from typing import Optional
from uuid import UUID

from pydantic import BaseModel, field_validator

from src.domain.shopify_apps.models import TRIGGER_TYPES


class ShopifyAppConfigUpdate(BaseModel):
    shop_domain: Optional[str] = None
    access_token: Optional[str] = None
    webhook_secret: Optional[str] = None


class ShopifyAppConfigResponse(BaseModel):
    project_id: UUID
    shop_domain: Optional[str]
    has_api_key: bool
    has_api_secret: bool
    has_access_token: bool
    has_webhook_secret: bool
    worker_name: Optional[str]
    worker_url: Optional[str]
    updated_at: datetime

    model_config = {"from_attributes": True}


class ShopifyAppFunctionCreate(BaseModel):
    name: str
    slug: str
    description: Optional[str] = None
    trigger_type: str
    cron_schedule: Optional[str] = None
    webhook_topic: Optional[str] = None
    code_ts: Optional[str] = None

    @field_validator("trigger_type")
    @classmethod
    def validate_trigger_type(cls, v: str) -> str:
        if v not in TRIGGER_TYPES:
            raise ValueError(f"trigger_type must be one of: {', '.join(TRIGGER_TYPES)}")
        return v

    @field_validator("slug")
    @classmethod
    def validate_slug(cls, v: str) -> str:
        import re
        if not re.match(r"^[a-z0-9][a-z0-9-]{0,98}[a-z0-9]?$", v):
            raise ValueError("slug must be lowercase alphanumeric with hyphens, 2-100 chars")
        return v


class ShopifyAppFunctionUpdate(BaseModel):
    name: Optional[str] = None
    description: Optional[str] = None
    trigger_type: Optional[str] = None
    cron_schedule: Optional[str] = None
    webhook_topic: Optional[str] = None
    code_ts: Optional[str] = None
    status: Optional[str] = None

    @field_validator("trigger_type")
    @classmethod
    def validate_trigger_type(cls, v: Optional[str]) -> Optional[str]:
        if v is not None and v not in TRIGGER_TYPES:
            raise ValueError(f"trigger_type must be one of: {', '.join(TRIGGER_TYPES)}")
        return v


class ShopifyAppFunctionResponse(BaseModel):
    id: UUID
    project_id: UUID
    name: str
    slug: str
    description: Optional[str]
    trigger_type: str
    cron_schedule: Optional[str]
    webhook_topic: Optional[str]
    has_code: bool
    status: str
    last_run_at: Optional[datetime]
    last_run_status: Optional[str]
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


class ShopifyAppFunctionDetailResponse(ShopifyAppFunctionResponse):
    code_ts: Optional[str]
    last_run_log: Optional[str]


class ShopifyAppPreviewTokenResponse(BaseModel):
    token: str
    expires_in: int
    worker_url: Optional[str]


class ShopifyAppInstallInstructions(BaseModel):
    worker_url: Optional[str]
    worker_name: Optional[str]
    shop_domain: Optional[str]
    steps: list[str]
    webhook_endpoints: list[dict]


class ShopifyAppResourcesResponse(BaseModel):
    project_id: UUID
    d1_database_id: Optional[str]
    d1_database_name: Optional[str]
    queue_name: Optional[str]
    r2_bucket_name: Optional[str]
    kv_namespace_id: Optional[str]
    kv_namespace_name: Optional[str]
    cloud_client_id: Optional[str]
    status: str
    last_error: Optional[str]
    provisioned_at: Optional[datetime]

    model_config = {"from_attributes": True}
