from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Request, status
from pydantic import ValidationError
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.core.responses import api_success
from app.schemas.sso import SsoTicketRequest
from app.services.security_state_service import client_ip
from app.services.sso_service import SsoService


router = APIRouter()


@router.post("/ticket")
async def create_ticket(request: Request, db: Session = Depends(get_db)) -> dict:
    raw_body = await request.body()
    try:
        payload = SsoTicketRequest.model_validate_json(raw_body)
    except ValidationError as exc:
        raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="接入用户参数不完整") from exc

    app_id = request.headers.get("X-App-Id", "").strip()
    timestamp = request.headers.get("X-Timestamp", "").strip()
    nonce = request.headers.get("X-Nonce", "").strip()
    signature = request.headers.get("X-Signature", "").strip()
    if not all((app_id, timestamp, nonce, signature)):
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="缺少应用签名信息")

    return api_success(
        SsoService.issue_ticket(
            db,
            app_id=app_id,
            timestamp=timestamp,
            nonce=nonce,
            signature=signature,
            raw_body=raw_body,
            payload=payload,
            ip=client_ip(request),
        )
    )
