# @File: backend/routers/whatsapp_contacts.py
# @Desc: Client-facing REST endpoints for the WhatsApp contact book.
from __future__ import annotations

from typing import Optional

from core.database import get_db
from dependencies.auth import get_current_user
from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
from pydantic import BaseModel, Field
from services.whatsapp import contacts as svc
from sqlalchemy.ext.asyncio import AsyncSession

router = APIRouter(
    prefix="/api/v1/client/whatsapp/contacts",
    tags=["whatsapp-client-contacts"],
)


def _user_id_of(current_user) -> str:
    user_id = str(getattr(current_user, "id", None) or getattr(current_user, "user_id", ""))
    if not user_id:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized")
    return user_id


class ContactCreate(BaseModel):
    phone_number: str = Field(min_length=5, max_length=40)
    display_name: Optional[str] = Field(default=None, max_length=128)
    tags: Optional[str] = Field(default=None, max_length=255)
    notes: Optional[str] = Field(default=None, max_length=2000)


class ContactUpdate(BaseModel):
    display_name: Optional[str] = Field(default=None, max_length=128)
    tags: Optional[str] = Field(default=None, max_length=255)
    notes: Optional[str] = Field(default=None, max_length=2000)
    is_opted_out: Optional[bool] = None


class BulkImport(BaseModel):
    csv_text: str = Field(min_length=1)


@router.get("")
async def list_contacts(
    search: Optional[str] = Query(default=None, max_length=128),
    tag: Optional[str] = Query(default=None, max_length=64),
    only_opted_in: bool = Query(default=False),
    limit: int = Query(default=50, ge=1, le=200),
    offset: int = Query(default=0, ge=0),
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
) -> dict:
    return await svc.list_contacts(
        db,
        _user_id_of(current_user),
        search=search,
        tag=tag,
        only_opted_in=only_opted_in,
        limit=limit,
        offset=offset,
    )


@router.post("", status_code=status.HTTP_201_CREATED)
async def create_contact(
    payload: ContactCreate,
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
) -> dict:
    return await svc.create_contact(
        db,
        _user_id_of(current_user),
        phone_number=payload.phone_number,
        display_name=payload.display_name,
        tags=payload.tags,
        notes=payload.notes,
    )


@router.patch("/{contact_id}")
async def update_contact(
    contact_id: int,
    payload: ContactUpdate,
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
) -> dict:
    return await svc.update_contact(
        db,
        _user_id_of(current_user),
        contact_id,
        display_name=payload.display_name,
        tags=payload.tags,
        notes=payload.notes,
        is_opted_out=payload.is_opted_out,
    )


@router.delete("/{contact_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_contact(
    contact_id: int,
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
) -> None:
    await svc.delete_contact(db, _user_id_of(current_user), contact_id)


@router.post("/import")
async def import_csv(
    payload: BulkImport,
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
) -> dict:
    return await svc.bulk_import_csv(db, _user_id_of(current_user), payload.csv_text)


@router.get("/tags/all")
async def list_tags(
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
) -> list[dict]:
    return await svc.list_tags(db, _user_id_of(current_user))