"""
Endpoints API para gestión de licencias
"""

from core.database import get_core_db
from core.security import get_current_user, has_role
from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy.orm import Session

from .dto import (
    LicenseCreateDTO,
    LicenseResponseDTO,
    LicenseUpdateDTO,
    LicenseUsageResponseDTO,
    LicenseValidationResponseDTO,
)
from .service import LicenseService

router = APIRouter(prefix="/licenses")


@router.post("/", response_model=LicenseResponseDTO, status_code=201)
async def create_license(
    license_data: LicenseCreateDTO,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    """
    Crea una nueva licencia para un tenant

    Requiere rol: admin
    """
    service = LicenseService(db)
    return service.create_license(license_data)


@router.get("/tenant/{tenant_id}", response_model=LicenseResponseDTO)
async def get_license_by_tenant(
    tenant_id: int,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Obtiene la licencia de un tenant específico
    """
    service = LicenseService(db)
    license = service.get_license_by_tenant(tenant_id)
    if not license:
        raise HTTPException(status_code=404, detail="License not found")
    return license


@router.put("/tenant/{tenant_id}", response_model=LicenseResponseDTO)
async def update_license(
    tenant_id: int,
    license_data: LicenseUpdateDTO,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    """
    Actualiza la licencia de un tenant

    Requiere rol: admin
    """
    service = LicenseService(db)
    license = service.update_license(tenant_id, license_data)
    if not license:
        raise HTTPException(status_code=404, detail="License not found")
    return license


@router.get("/validate/{tenant_id}", response_model=LicenseValidationResponseDTO)
async def validate_license(
    tenant_id: int,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Valida si la licencia de un tenant está activa y vigente
    """
    service = LicenseService(db)
    validation = service.validate_license(tenant_id)
    return LicenseValidationResponseDTO(**validation)


@router.get("/usage/{tenant_id}", response_model=LicenseUsageResponseDTO)
async def get_license_usage(
    tenant_id: int,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Obtiene el uso actual de la licencia de un tenant
    """
    service = LicenseService(db)
    usage = service.get_usage(tenant_id)
    if not usage:
        raise HTTPException(status_code=404, detail="License not found")
    return usage


@router.get("/my-license", response_model=LicenseResponseDTO)
async def get_my_license(
    request: Request,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Obtiene la licencia del tenant del usuario actual
    """
    tenant_id = getattr(request.state, "tenant_id", None)
    if not tenant_id:
        raise HTTPException(status_code=400, detail="Tenant ID not found in request")

    service = LicenseService(db)
    license = service.get_license_by_tenant(tenant_id)
    if not license:
        raise HTTPException(status_code=404, detail="License not found")
    return license
