"""Site domain APIs — Phase 11.1."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_pagination, require_tenant
from app.api.permissions import require_permissions
from app.permissions.definitions import (
    DOMAINS_CREATE,
    DOMAINS_DELETE,
    DOMAINS_UPDATE,
    DOMAINS_VIEW,
)
from app.schemas.sites import (
    ExperienceSiteDomainCreate,
    ExperienceSiteDomainRead,
    ExperienceSiteDomainUpdate,
)
from app.services.sites import ExperienceSiteDomainService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post(
    "", response_model=ExperienceSiteDomainRead, status_code=status.HTTP_201_CREATED
)
async def create_domain(
    body: ExperienceSiteDomainCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DOMAINS_CREATE)),
):
    return await ExperienceSiteDomainService(db).create(tenant_id, body, actor=user)


@router.get("", response_model=list[ExperienceSiteDomainRead])
async def list_domains(
    site_id: UUID = Query(...),
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(DOMAINS_VIEW)),
):
    return await ExperienceSiteDomainService(db).list_by_site(
        tenant_id, site_id, offset=pagination.offset, limit=pagination.page_size
    )


@router.get("/{domain_id}", response_model=ExperienceSiteDomainRead)
async def get_domain(
    domain_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(DOMAINS_VIEW)),
):
    return await ExperienceSiteDomainService(db).get(tenant_id, domain_id)


@router.patch("/{domain_id}", response_model=ExperienceSiteDomainRead)
async def update_domain(
    domain_id: UUID,
    body: ExperienceSiteDomainUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DOMAINS_UPDATE)),
):
    return await ExperienceSiteDomainService(db).update(
        tenant_id, domain_id, body, actor=user
    )


@router.post("/{domain_id}/delete", response_model=ExperienceSiteDomainRead)
async def soft_delete_domain(
    domain_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DOMAINS_DELETE)),
):
    return await ExperienceSiteDomainService(db).soft_delete(
        tenant_id, domain_id, actor=user
    )
