from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from app.api.v1.deps import require_role
from app.api.v1.endpoints.merchants import _branch_out
from app.db.session import get_db
from app.models.user import User, UserRole
from app.schemas.branch import BranchOut
from app.schemas.customer import CustomerProfileOut, CustomerProfileUpdateRequest
from app.services import customer_profile as customer_profile_service
from app.services import favorites as favorites_service
from app.services.reviews import get_branch_rating_stats

router = APIRouter(prefix="/customer", tags=["customer"])


@router.get("/favorites", response_model=list[BranchOut])
def list_favorites(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> list[BranchOut]:
    """Most-recently-favorited first (see
    app.services.favorites.list_favorite_branches). is_favorited will
    always be True on every result here — still computed the normal
    way (bulk favorited_ids) rather than hardcoded, so this stays
    correct if that ever changes."""
    branches = favorites_service.list_favorite_branches(db, current_user.id)
    ids = [b.id for b in branches]
    stats = get_branch_rating_stats(db, ids)
    favorited = favorites_service.get_favorited_branch_ids(db, current_user.id, ids)
    return [_branch_out(db, b, stats, current_user.id, favorited) for b in branches]


@router.get("/profile", response_model=CustomerProfileOut)
def get_profile(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> CustomerProfileOut:
    """Optional profile details — never populated unless the customer
    actually filled them in, since profile completion is fully
    skippable (see app.models.customer_profile.CustomerProfile)."""
    profile = customer_profile_service.get_or_create_profile(db, current_user.id)
    return CustomerProfileOut.model_validate(profile)


@router.patch("/profile", response_model=CustomerProfileOut)
def update_profile(
    payload: CustomerProfileUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> CustomerProfileOut:
    """Partial update — only fields actually sent are changed, so the
    client can save one profile-completion screen at a time (or just
    the default delivery address from checkout) without resending
    everything else."""
    profile = customer_profile_service.get_or_create_profile(db, current_user.id)
    for field, value in payload.model_dump(exclude_unset=True).items():
        setattr(profile, field, value)
    db.commit()
    db.refresh(profile)
    return CustomerProfileOut.model_validate(profile)
