import uuid

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.api.v1.deps import require_role
from app.db.session import get_db
from app.models.branch import Branch
from app.models.merchant import Merchant
from app.models.promo_code import PromoCode
from app.models.user import User, UserRole
from app.schemas.promo_code import (
    PromoCodeCreateRequest,
    PromoCodeOut,
    PromoCodeUpdateRequest,
)

router = APIRouter(prefix="/promo-codes", tags=["promo-codes"])

_ADMIN_ROLES = {UserRole.ADMIN.value, UserRole.SUPERADMIN.value}
_NOT_FOUND = HTTPException(
    status_code=status.HTTP_404_NOT_FOUND, detail="Promo code not found."
)
_CODE_EXISTS = HTTPException(
    status_code=status.HTTP_409_CONFLICT,
    detail="A promo code with this code already exists.",
)


def _get_promo_or_404(db: Session, promo_id: uuid.UUID) -> PromoCode:
    promo = db.query(PromoCode).filter(PromoCode.id == promo_id).first()
    if promo is None:
        raise _NOT_FOUND
    return promo


def _require_owns_merchant(
    db: Session, merchant_id: uuid.UUID, current_user: User
) -> None:
    merchant = (
        db.query(Merchant)
        .filter(Merchant.id == merchant_id, Merchant.deleted_at.is_(None))
        .first()
    )
    if merchant is None or merchant.owner_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You don't own this merchant.",
        )


def _require_promo_manager(db: Session, promo: PromoCode, current_user: User) -> None:
    """Admins manage any code; a supplier can only manage codes scoped
    to their own merchant — never a platform-wide one (merchant_id is
    None), which only an admin can create or touch."""
    if current_user.role in _ADMIN_ROLES:
        return
    if promo.merchant_id is None:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You don't manage this promo code.",
        )
    _require_owns_merchant(db, promo.merchant_id, current_user)


@router.post("", response_model=PromoCodeOut)
def create_promo_code(
    payload: PromoCodeCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(
        require_role(UserRole.SUPPLIER, UserRole.ADMIN, UserRole.SUPERADMIN)
    ),
) -> PromoCodeOut:
    """An admin can create a platform-wide code (merchant_id omitted)
    or scope one to any merchant, optionally narrowed to one branch. A
    supplier must always scope it to a merchant they own — never
    platform-wide, and never someone else's merchant — and may
    likewise narrow it to one of their own branches."""
    if current_user.role not in _ADMIN_ROLES:
        if payload.merchant_id is None:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
                detail="merchant_id is required.",
            )
        _require_owns_merchant(db, payload.merchant_id, current_user)

    if payload.branch_id is not None:
        branch = (
            db.query(Branch)
            .filter(Branch.id == payload.branch_id, Branch.deleted_at.is_(None))
            .first()
        )
        if branch is None or branch.merchant_id != payload.merchant_id:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
                detail="branch_id must belong to merchant_id.",
            )

    if db.query(PromoCode).filter(PromoCode.code == payload.code).first() is not None:
        raise _CODE_EXISTS

    promo = PromoCode(
        code=payload.code,
        merchant_id=payload.merchant_id,
        branch_id=payload.branch_id,
        created_by_id=current_user.id,
        discount_type=payload.discount_type,
        discount_value=payload.discount_value,
        max_discount_amount=payload.max_discount_amount,
        min_order_amount=payload.min_order_amount,
        usage_limit=payload.usage_limit,
        usage_limit_per_customer=payload.usage_limit_per_customer,
        valid_from=payload.valid_from,
        valid_until=payload.valid_until,
    )
    db.add(promo)
    db.commit()
    db.refresh(promo)
    return PromoCodeOut.model_validate(promo)


@router.get("", response_model=list[PromoCodeOut])
def list_promo_codes(
    db: Session = Depends(get_db),
    current_user: User = Depends(
        require_role(UserRole.SUPPLIER, UserRole.ADMIN, UserRole.SUPERADMIN)
    ),
) -> list[PromoCodeOut]:
    """Admins see every code, platform-wide and merchant-scoped alike.
    A supplier only sees codes scoped to a merchant they own — never
    platform-wide codes they didn't create and can't manage."""
    query = db.query(PromoCode)
    if current_user.role not in _ADMIN_ROLES:
        owned_merchant_ids = db.query(Merchant.id).filter(
            Merchant.owner_id == current_user.id
        )
        query = query.filter(PromoCode.merchant_id.in_(owned_merchant_ids))
    return [
        PromoCodeOut.model_validate(p)
        for p in query.order_by(PromoCode.created_at.desc()).all()
    ]


@router.patch("/{promo_id}", response_model=PromoCodeOut)
def update_promo_code(
    promo_id: uuid.UUID,
    payload: PromoCodeUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(
        require_role(UserRole.SUPPLIER, UserRole.ADMIN, UserRole.SUPERADMIN)
    ),
) -> PromoCodeOut:
    promo = _get_promo_or_404(db, promo_id)
    _require_promo_manager(db, promo, current_user)

    for field, value in payload.model_dump(exclude_unset=True).items():
        setattr(promo, field, value)
    db.commit()
    db.refresh(promo)
    return PromoCodeOut.model_validate(promo)
