from __future__ import annotations

from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.core.dependencies import get_current_token_payload
from app.core.responses import api_success
from app.schemas.auth import CaptchaResponse, LoginRequest, LoginResponse, SendSmsRequest
from app.schemas.sso import SsoExchangeRequest
from app.services.auth_service import AuthService
from app.services.captcha_service import CaptchaService
from app.services.security_state_service import client_ip
from app.services.sso_service import SsoService

router = APIRouter()


@router.get("/captcha")
def captcha() -> dict:
    return api_success(CaptchaResponse.model_validate(CaptchaService.create()).model_dump())


@router.post("/sms/send")
def send_sms(payload: SendSmsRequest, request: Request, db: Session = Depends(get_db)) -> dict:
    AuthService.send_sms_code(db, payload.phone, payload.captchaId, payload.captchaCode, client_ip(request))
    return api_success(message="发送成功")


@router.post("/login")
def login(payload: LoginRequest, db: Session = Depends(get_db)) -> dict:
    result = AuthService.login_with_sms(db, payload.phone, payload.code)
    return api_success(LoginResponse.model_validate(result).model_dump(mode="json"))


@router.post("/sso/exchange")
def exchange_sso(payload: SsoExchangeRequest, request: Request, db: Session = Depends(get_db)) -> dict:
    result = SsoService.exchange(db, code=payload.code, ip=client_ip(request))
    return api_success(LoginResponse.model_validate(result).model_dump(mode="json"))


@router.post("/logout")
def logout(token_payload: dict = Depends(get_current_token_payload)) -> dict:
    AuthService.logout(token_payload)
    return api_success()
