"""Tenant resolution and safety helpers."""
from typing import Optional

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

from app.core.models.customer import Customer
from app.core.models.tenant import Tenant
from app.core.models.user import User


async def resolve_public_tenant_id(
    db: AsyncSession,
    tenant_id: Optional[int] = None,
    request: Optional[Request] = None,
) -> int:
    """Resolve tenant for public storefront requests.

    Public routes may accept tenant_id during local development. If omitted, try
    the request host, then fall back to the lowest active tenant for single-store
    deployments.
    """
    if tenant_id is not None:
        return int(tenant_id)

    host = ""
    if request is not None:
        # 优先读反向代理/客户端透传的 x-forwarded-host，fallback 到 host
        raw = (
            request.headers.get("x-forwarded-host")
            or request.headers.get("host", "")
        )
        host = raw.split(":")[0].strip().lower()

    if host:
        result = await db.execute(
            select(Tenant.id).where(Tenant.domain == host, Tenant.status == "active")
        )
        resolved = result.scalar_one_or_none()
        if resolved is not None:
            return int(resolved)

    result = await db.execute(
        select(Tenant.id).where(Tenant.status == "active").order_by(Tenant.id.asc()).limit(1)
    )
    fallback = result.scalar_one_or_none()
    return int(fallback) if fallback is not None else 1


def tenant_id_for_customer(customer: Customer, requested_tenant_id: Optional[int] = None) -> int:
    """Return the customer's tenant id and reject cross-tenant overrides."""
    actual = int(customer.tenant_id)
    if requested_tenant_id is not None and int(requested_tenant_id) != actual:
        raise HTTPException(status_code=403, detail="租户不匹配")
    return actual


def tenant_id_for_admin(user: User, requested_tenant_id: Optional[int] = None) -> int:
    """Return the admin user's tenant id and reject cross-tenant overrides."""
    actual = int(user.tenant_id)
    if requested_tenant_id is not None and int(requested_tenant_id) != actual:
        raise HTTPException(status_code=403, detail="租户不匹配")
    return actual
