"""Tax rate routes — list, create, update, delete."""

from __future__ import annotations

import uuid

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

from app.core.db import get_db
from app.deps import require_permission
from app.schemas.tax import TaxRateCreate, TaxRateUpdate
from app.services import tax_service

router = APIRouter(prefix="/api/v1/taxes", tags=["taxes"])


@router.get("")
async def list_tax_rates(
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("taxes:read")),
):
    """List all tax rates for the current tenant."""
    tenant_id = uuid.UUID(current_user["tenant_id"])
    return await tax_service.list_tax_rates(db, tenant_id)


@router.post("", status_code=status.HTTP_201_CREATED)
async def create_tax_rate(
    body: TaxRateCreate,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("taxes:write")),
):
    """Create a tax rate. Requires admin permission."""
    tenant_id = uuid.UUID(current_user["tenant_id"])
    user_id = uuid.UUID(current_user["user_id"])


    data = body.model_dump()
    return await tax_service.create_tax_rate(db, tenant_id, user_id, data)


@router.patch("/{tax_id}")
async def update_tax_rate(
    tax_id: str,
    body: TaxRateUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("taxes:write")),
):
    """Update a tax rate. Requires admin permission."""
    tenant_id = uuid.UUID(current_user["tenant_id"])
    user_id = uuid.UUID(current_user["user_id"])


    try:
        tid = uuid.UUID(tax_id)
    except ValueError:
        raise HTTPException(400, detail={"detail": "Invalid tax_id", "code": "invalid_id"}) from None

    data = body.model_dump(exclude_unset=True)
    result = await tax_service.update_tax_rate(db, tenant_id, user_id, tid, data)
    if result is None:
        raise HTTPException(404, detail={"detail": "Tax rate not found", "code": "not_found"})
    return result


@router.delete("/{tax_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_tax_rate(
    tax_id: str,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("taxes:write")),
):
    """Delete a tax rate. Requires admin permission."""
    tenant_id = uuid.UUID(current_user["tenant_id"])
    user_id = uuid.UUID(current_user["user_id"])


    try:
        tid = uuid.UUID(tax_id)
    except ValueError:
        raise HTTPException(400, detail={"detail": "Invalid tax_id", "code": "invalid_id"}) from None

    deleted = await tax_service.delete_tax_rate(db, tenant_id, user_id, tid)
    if not deleted:
        raise HTTPException(404, detail={"detail": "Tax rate not found", "code": "not_found"})
