from fastapi import Depends, Header, Query

from app.application.exceptions import ValidationError
from app.application.services.company_service import CompanyService
from app.domain.entities.user_registration import UserRegistration
from app.infrastructure.repositories.mysql_utils import is_uuid
from app.presentation.auth_dependencies import get_current_user
from app.presentation.dependencies import get_company_service


def is_company_document_id(value: str) -> bool:
    return is_uuid(value)


async def _resolve_company_document_id(
    company_id: str,
    current_user: UserRegistration,
    service: CompanyService,
) -> str:
    if not is_company_document_id(company_id):
        raise ValidationError(
            "Invalid company_id. Use the company `id` from GET /api/v1/companies "
            f"(UUID), not the slug '{company_id}'."
        )
    await service.get_company(current_user, company_id)
    return company_id


async def get_validated_company_id_query(
    company_id: str | None = Query(None, description="Company document id from GET /companies"),
    x_company_id: str | None = Header(None, alias="X-Company-Id"),
    current_user: UserRegistration = Depends(get_current_user),
    service: CompanyService = Depends(get_company_service),
) -> str:
    resolved = (company_id or x_company_id or "").strip()
    if not resolved:
        raise ValidationError("company_id is required")
    return await _resolve_company_document_id(resolved, current_user, service)


async def get_validated_company_id_path(
    company_id: str,
    current_user: UserRegistration = Depends(get_current_user),
    service: CompanyService = Depends(get_company_service),
) -> str:
    return await _resolve_company_document_id(company_id, current_user, service)
