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_admin
from app.core.responses import api_success
from app.models.admin import Admin
from app.schemas.admin import AdminLoginRequest, AdminLoginResponse
from app.services.admin_permission_service import permissions_for
from app.services.admin_service import AdminAuthService
from app.services.auth_service import AuthService
from app.services.security_state_service import client_ip
from app.core.dependencies import get_current_token_payload

router = APIRouter()


@router.post("/login")
def login(payload: AdminLoginRequest, request: Request, db: Session = Depends(get_db)) -> dict:
    result = AdminAuthService.login(db, payload.username, payload.password, client_ip(request))
    return api_success(AdminLoginResponse.model_validate(result).model_dump(mode="json"))


@router.get("/profile")
def profile(current_admin: Admin = Depends(get_current_admin)) -> dict:
    return api_success({
        "id": current_admin.id, "username": current_admin.username, "name": current_admin.name,
        "status": current_admin.status, "isSuperAdmin": bool(current_admin.is_super_admin),
        "mustChangePassword": bool(current_admin.must_change_password),
        "permissions": sorted(permissions_for(current_admin)),
    })


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