import uuid

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.core.permissions import require_permission
from app.core.security import AuthContext, get_auth_context
from app.crud.base import CRUDBase
from app.models.identity import Vendor
from app.schemas.identity import VendorCreate, VendorRead, VendorUpdate

router = APIRouter(prefix="/vendors", tags=["vendors"])
crud = CRUDBase[Vendor, VendorCreate, VendorUpdate](Vendor)


@router.get("/me", response_model=VendorRead)
async def get_my_vendor(
    ctx: AuthContext = Depends(get_auth_context),
    db: AsyncSession = Depends(get_db),
) -> Vendor:
    """The Public Portal's own "who am I" for its brand header (shows the
    caller's own vendor organization_name instead of the app's generic
    title — see PortalLayout.tsx/PortalBrand.tsx). No require_permission:
    a vendor (Public Portal) caller holds no internal role/module grant at
    all (see app/core/permissions.py), so every other route on this router
    is unreachable for one — this is deliberately the one exception,
    scoped to the caller's own ctx.vendor_id only, mirroring GET
    /tenants/me's same "read my own scoped record, no broader grant
    needed" posture."""
    if ctx.vendor_id is None:
        raise HTTPException(status_code=404, detail="Not a vendor account")
    return await crud.get(db, ctx.tenant_id, ctx.vendor_id)


@router.get("", response_model=list[VendorRead])
async def list_vendors(
    skip: int = 0,
    limit: int = 100,
    ctx: AuthContext = Depends(get_auth_context),
    db: AsyncSession = Depends(get_db),
    _: AuthContext = Depends(require_permission("settings", "view")),
) -> list[Vendor]:
    return await crud.list(db, ctx.tenant_id, skip=skip, limit=limit)


@router.get("/{vendor_id}", response_model=VendorRead)
async def get_vendor(
    vendor_id: uuid.UUID,
    ctx: AuthContext = Depends(get_auth_context),
    db: AsyncSession = Depends(get_db),
    _: AuthContext = Depends(require_permission("settings", "view")),
) -> Vendor:
    return await crud.get(db, ctx.tenant_id, vendor_id)


@router.post("", response_model=VendorRead, status_code=status.HTTP_201_CREATED)
async def create_vendor(
    payload: VendorCreate,
    ctx: AuthContext = Depends(get_auth_context),
    db: AsyncSession = Depends(get_db),
    _: AuthContext = Depends(require_permission("settings", "create")),
) -> Vendor:
    return await crud.create(db, ctx.tenant_id, payload)


@router.patch("/{vendor_id}", response_model=VendorRead)
async def update_vendor(
    vendor_id: uuid.UUID,
    payload: VendorUpdate,
    ctx: AuthContext = Depends(get_auth_context),
    db: AsyncSession = Depends(get_db),
    _: AuthContext = Depends(require_permission("settings", "edit")),
) -> Vendor:
    return await crud.update(db, ctx.tenant_id, vendor_id, payload)


@router.delete("/{vendor_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_vendor(
    vendor_id: uuid.UUID,
    ctx: AuthContext = Depends(get_auth_context),
    db: AsyncSession = Depends(get_db),
    _: AuthContext = Depends(require_permission("settings", "delete")),
) -> None:
    await crud.delete(db, ctx.tenant_id, vendor_id)
