"""Registration, login, current user profile."""

from __future__ import annotations

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

from aif_platform.server.db.connection import get_db
from aif_platform.server.api.deps import get_current_user
from aif_platform.server.models.persistence import PlatformUser
from aif_platform.server.schemas import (
    ChangePasswordRequest,
    LoginRequest,
    OkResponse,
    OrgBrief,
    RegisterRequest,
    TokenResponse,
    UserMeResponse,
)
from aif_platform.server.services.auth_service import (
    change_password,
    login_user,
    register_user,
)
from aif_platform.server.services.org_service import list_memberships_for_user

router = APIRouter(prefix="/auth", tags=["auth"])


@router.post("/register", response_model=TokenResponse)
async def register(body: RegisterRequest, db: AsyncSession = Depends(get_db)):
    _user, token = await register_user(
        db,
        email=body.email,
        password=body.password,
        org_name=body.org_name,
    )
    return TokenResponse(access_token=token)


@router.post("/login", response_model=TokenResponse)
async def login(body: LoginRequest, db: AsyncSession = Depends(get_db)):
    _user, token = await login_user(db, email=body.email, password=body.password)
    return TokenResponse(access_token=token)


@router.get("/me", response_model=UserMeResponse)
async def me(
    user: PlatformUser = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    rows = await list_memberships_for_user(db, user.id)
    orgs = [OrgBrief(id=o.id, name=o.name, role=m.role) for m, o in rows]
    return UserMeResponse(
        id=user.id,
        email=user.email,
        is_platform_admin=user.is_platform_admin,
        organizations=orgs,
    )


@router.post("/change-password", response_model=OkResponse)
async def change_password_route(
    body: ChangePasswordRequest,
    user: PlatformUser = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    await change_password(
        db,
        user_id=user.id,
        current_password=body.current_password,
        new_password=body.new_password,
    )
    return OkResponse()
