"""Rutas para gestión de invitaciones de usuarios."""

import logging

from core.database import get_core_db
from core.security import get_current_user, validate_access_to_resource
from core.config import settings
from fastapi import APIRouter, Depends, Query, Request
from sqlalchemy.orm import Session

from .dto import CreateInviteDTO, InviteResponseDTO
from .service import InviteService

router = APIRouter(prefix="/invites", tags=["Invites"])

logger = logging.getLogger(__name__)


@router.post("", response_model=InviteResponseDTO, status_code=201)
async def create_invite(
    data: CreateInviteDTO,
    request: Request,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Genera un token de invitación para que un usuario externo se registre.
    Requiere permiso user.create.
    """
    # Validar acceso (user.create) y obtener tenant_id
    validate_access_to_resource(
        db,
        data.company_id,
        current_user,
        required_permissions=["user.create"],
    )

    tenant_slug: str = current_user.get("tenant_slug") or ""
    created_by: str = current_user.get("sub") or ""
    base_url = settings.APP_PUBLIC_URL.rstrip("/")

    service = InviteService(db)
    return await service.create_invite(
        data=data,
        created_by=created_by,
        tenant_slug=tenant_slug,
        base_url=base_url,
    )
