"""
联系人 API 路由 — /api/customers/{cid}/contacts & /api/contacts/{id}
V5.0: 实现客户下联系人的完整 CRUD
"""
from __future__ import annotations

import uuid
from fastapi import APIRouter, Depends, Body
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_current_user
from app.db.database import get_db
from app.schemas.auth import CurrentUserPayload
from app.schemas.response import ok
from app.services import contact_service

router = APIRouter(tags=["联系人"])


@router.get("/customers/{customer_id}/contacts", summary="列出客户下所有联系人")
async def list_contacts(
    customer_id: uuid.UUID,
    db: AsyncSession = Depends(get_db),
    _: CurrentUserPayload = Depends(get_current_user),
) -> dict:
    items = await contact_service.list_contacts(db, customer_id)
    return ok(data=items)


@router.post("/customers/{customer_id}/contacts", summary="新增联系人")
async def create_contact(
    customer_id: uuid.UUID,
    name: str = Body(..., embed=True),
    phone: str | None = Body(None, embed=True),
    title: str | None = Body(None, embed=True),
    db: AsyncSession = Depends(get_db),
    _: CurrentUserPayload = Depends(get_current_user),
) -> dict:
    result = await contact_service.create_contact(
        db, customer_id, {"name": name, "phone": phone, "title": title}
    )
    return ok(data=result, message="联系人创建成功")


@router.put("/contacts/{contact_id}", summary="编辑联系人")
async def update_contact(
    contact_id: uuid.UUID,
    name: str | None = Body(None, embed=True),
    phone: str | None = Body(None, embed=True),
    title: str | None = Body(None, embed=True),
    db: AsyncSession = Depends(get_db),
    _: CurrentUserPayload = Depends(get_current_user),
) -> dict:
    data = {}
    if name is not None:
        data["name"] = name
    if phone is not None:
        data["phone"] = phone
    if title is not None:
        data["title"] = title
    result = await contact_service.update_contact(db, contact_id, data)
    return ok(data=result, message="联系人更新成功")


@router.delete("/contacts/{contact_id}", summary="删除联系人 (软删除)")
async def delete_contact(
    contact_id: uuid.UUID,
    db: AsyncSession = Depends(get_db),
    _: CurrentUserPayload = Depends(get_current_user),
) -> dict:
    await contact_service.delete_contact(db, contact_id)
    return ok(message="联系人已删除")
