# @File: backend/routers/whatsapp_devices.py
# @Desc: Client-facing REST endpoints for the WhatsApp device pairing flow.
#        All routes require an authenticated DoItEasy user and resolve the
#        caller's active subscription inside the service layer.
from __future__ import annotations

from typing import Optional

from core.database import get_db
from dependencies.auth import get_current_user  # shared DoItEasy auth dependency
from fastapi import APIRouter, Body, Depends, HTTPException, status
from pydantic import BaseModel, Field
from services.whatsapp import devices as svc
from sqlalchemy.ext.asyncio import AsyncSession

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


class DeviceCreate(BaseModel):
    display_name: str = Field(default="WhatsApp Device", max_length=128)


class DeviceSimulate(BaseModel):
    phone_number: Optional[str] = Field(default=None, max_length=40)


@router.get("")
async def list_devices(
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
) -> list[dict]:
    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 await svc.list_devices(db, user_id)


@router.post("", status_code=status.HTTP_201_CREATED)
async def create_device(
    payload: DeviceCreate,
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
) -> dict:
    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 await svc.create_device(db, user_id, payload.display_name)


@router.post("/{device_id}/qr")
async def request_qr(
    device_id: int,
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
) -> dict:
    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 await svc.request_qr(db, user_id, device_id)


@router.get("/{device_id}")
async def poll_status(
    device_id: int,
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
) -> dict:
    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 await svc.poll_status(db, user_id, device_id)


@router.post("/{device_id}/simulate-paired")
async def simulate_paired(
    device_id: int,
    payload: DeviceSimulate = Body(default_factory=DeviceSimulate),
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
) -> dict:
    """Test-only helper that marks a device connected without scanning a QR.

    Useful for QA and for demoing downstream features (campaigns, AI, etc.).
    """
    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 await svc.simulate_paired(db, user_id, device_id, payload.phone_number)


@router.delete("/{device_id}")
async def archive_device(
    device_id: int,
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
) -> dict:
    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 await svc.archive_device(db, user_id, device_id)