"""Organization list and rename (tenant)."""

from __future__ import annotations

import uuid

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

from aif_platform.server.api.deps import get_current_user
from aif_platform.server.db.connection import get_db
from aif_platform.server.models.persistence import PlatformUser
from aif_platform.server.schemas import OrgBrief, OrgListResponse, OrgPatchResponse, OrgUpdateRequest
from aif_platform.server.services.org_service import list_memberships_for_user, update_org_name

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


@router.get("", response_model=OrgListResponse)
async def list_orgs(
    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 OrgListResponse(organizations=orgs)


@router.patch("/{org_id}", response_model=OrgPatchResponse)
async def patch_org(
    org_id: uuid.UUID,
    body: OrgUpdateRequest,
    user: PlatformUser = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    org = await update_org_name(db, user_id=user.id, org_id=org_id, name=body.name)
    return OrgPatchResponse(id=org.id, name=org.name, created_at=org.created_at)
