"""The Portal menu's logo — the tenant's (Settings › Portal appearance) or a
portal role's own (Portal Roles › Appearance)."""

import uuid

from fastapi import HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.upload import UploadedFile

# The portal logo (PortalMenuSettings.logo_file_id) is an ordinary tenant upload
# — any tenant member can already upload — so its type and size are checked
# here, when it is chosen as the logo, rather than in the generic upload route.
_LOGO_TYPES = {"image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml"}
_LOGO_MAX_BYTES = 2 * 1024 * 1024


async def check_logo_file(db: AsyncSession, tenant_id: uuid.UUID, file_id: uuid.UUID) -> None:
    """A Portal menu logo (the tenant's, or a portal role's own): an image
    this tenant uploaded, of an allowed type and size."""
    upload = (await db.execute(select(UploadedFile).where(UploadedFile.id == file_id, UploadedFile.tenant_id == tenant_id))).scalar_one_or_none()
    if upload is None:
        raise HTTPException(status_code=422, detail="The logo file was not found — upload it again.")
    if upload.content_type not in _LOGO_TYPES:
        raise HTTPException(status_code=422, detail="The logo must be a PNG, JPEG, GIF, WebP or SVG image.")
    if upload.size_bytes > _LOGO_MAX_BYTES:
        raise HTTPException(status_code=422, detail="The logo must be 2 MB or smaller.")
