"""Lead CRM APIs — Phase 6.1."""
from __future__ import annotations

from uuid import UUID

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

from app.api.deps import get_db, get_pagination, require_tenant
from app.core.security import get_current_user
from app.schemas.foundation import LeadAssignRequest, LeadCreate, LeadRead, LeadUpdate
from app.services.lead_service import LeadService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=LeadRead, status_code=status.HTTP_201_CREATED)
async def create_lead(
    body: LeadCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await LeadService(db).create(tenant_id, body, actor=user)


@router.get("", response_model=list[LeadRead])
async def list_leads(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(get_current_user),
):
    return await LeadService(db).list(
        tenant_id, offset=pagination.offset, limit=pagination.page_size
    )


@router.get("/{lead_id}", response_model=LeadRead)
async def get_lead(
    lead_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(get_current_user),
):
    return await LeadService(db).get(tenant_id, lead_id)


@router.patch("/{lead_id}", response_model=LeadRead)
async def update_lead(
    lead_id: UUID,
    body: LeadUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await LeadService(db).update(tenant_id, lead_id, body, actor=user)


@router.post("/{lead_id}/assign", response_model=LeadRead)
async def assign_lead(
    lead_id: UUID,
    body: LeadAssignRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await LeadService(db).assign(tenant_id, lead_id, body, actor=user)


@router.post("/{lead_id}/delete", response_model=LeadRead)
async def soft_delete_lead(
    lead_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await LeadService(db).soft_delete(tenant_id, lead_id, actor=user)


@router.post("/{lead_id}/restore", response_model=LeadRead)
async def restore_lead(
    lead_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await LeadService(db).restore(tenant_id, lead_id, actor=user)
