"""Auth dependencies for FastAPI routes."""

from typing import Optional

from fastapi import Depends, Header, HTTPException
from sqlalchemy.orm import Session

from ..config import settings
from ..db import get_db
from ..models import Partner
from ..services import partner_service


def get_partner_from_api_key(
    x_api_key: Optional[str] = Header(default=None, alias="X-API-Key"),
    api_key: Optional[str] = None,
    db: Session = Depends(get_db),
) -> Partner:
    """Authenticate partner using API key header (or query param in dev)."""

    key_value = x_api_key or api_key
    if api_key and settings.app_env == "prod":
        raise HTTPException(status_code=400, detail="Query API key not allowed in prod")
    if not key_value:
        raise HTTPException(status_code=401, detail="Missing API key")

    partner = partner_service.authenticate_partner(db, key_value)
    if not partner:
        raise HTTPException(status_code=401, detail="Invalid API key")
    return partner


def require_admin_api_key(
    x_admin_key: Optional[str] = Header(default=None, alias="X-Admin-Key"),
    admin_key: Optional[str] = None,
) -> None:
    """Validate admin key for protected endpoints (query param in dev only)."""

    if admin_key and settings.app_env == "prod":
        raise HTTPException(status_code=400, detail="Query admin key not allowed in prod")

    key_value = x_admin_key or admin_key
    if settings.admin_api_key:
        if not key_value or key_value != settings.admin_api_key:
            raise HTTPException(status_code=401, detail="Invalid admin key")
    elif not settings.allow_unsafe_admin:
        raise HTTPException(status_code=401, detail="Admin key not configured")
