"""Auth router: registration and login endpoints."""

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

from app.dependencies import get_db
from app.schemas.auth import LoginRequest, RegisterRequest, TokenResponse
from app.schemas.common import APIEnvelope
from app.services import auth_service

router = APIRouter(tags=["auth"])


@router.post("/auth/register", response_model=APIEnvelope)
async def register(body: RegisterRequest, db: AsyncSession = Depends(get_db)):
    """Public endpoint — register a new user."""
    user = await auth_service.register(db, body.username, body.password)
    return APIEnvelope(
        status="success",
        data={
            "id": user.id,
            "username": user.username,
            "role": user.role,
            "has_access": user.has_access,
        },
    )


@router.post("/auth/login", response_model=APIEnvelope)
async def login(body: LoginRequest, db: AsyncSession = Depends(get_db)):
    """Public endpoint — login and receive a JWT."""
    token = await auth_service.login(db, body.username, body.password)
    token_resp = TokenResponse(access_token=token)
    return APIEnvelope(status="success", data=token_resp.model_dump())
