from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.deps import require_role
from app.database import get_db
from app.models.user import User
from app.schemas.common import ApiResponse
from app.schemas.token import RefreshRequest
from app.schemas.user import UserLogin, UserResponse
from app.services import auth_service

router = APIRouter()


@router.post("/login", response_model=ApiResponse)
async def admin_login(data: UserLogin, db: AsyncSession = Depends(get_db)):
    user, tokens = await auth_service.admin_login(db, data)
    return ApiResponse(data={"user": user, "tokens": tokens})


@router.post("/refresh", response_model=ApiResponse)
async def admin_refresh(data: RefreshRequest, db: AsyncSession = Depends(get_db)):
    tokens = await auth_service.refresh(db, data.refresh_token)
    return ApiResponse(data=tokens)


@router.post("/logout", response_model=ApiResponse)
async def admin_logout(data: RefreshRequest):
    await auth_service.logout(data.refresh_token)
    return ApiResponse(data=None)


@router.get("/me", response_model=ApiResponse)
async def admin_me(
    current_user: User = Depends(require_role("admin", "super_admin")),
):
    return ApiResponse(data=UserResponse.model_validate(current_user))
