"""The signed-in surface: the caller's own account, and the invite roster.

These are the two routes that exercise the authorization layer end-to-end —
`current_user` (signed in AND invited) and `current_superadmin`. Without them
the dependencies in deps.py would be dead code, and dead auth code is untested
auth code.

The invite roster is deliberately READ-ONLY. Issuing and revoking invites from
the UI is F6 in the plan; until then invites are rows written by hand or by the
seed script, and this route is how an operator confirms what is actually there.
"""

from __future__ import annotations

from datetime import datetime

from fastapi import APIRouter, Depends
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.orm import Session

from ..db import get_db
from ..deps import current_superadmin, current_user
from ..models.identity import Invite, User
from ..services.roles import label_for

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


class AccountOut(BaseModel):
    username: str
    display_name: str
    email: str
    role: str
    role_label: str
    created_at: datetime | None = None
    last_login_at: datetime | None = None


class InviteOut(BaseModel):
    email: str
    role: str
    role_label: str
    note: str
    created_at: datetime | None = None
    redeemed_at: datetime | None = None


@router.get("/account", response_model=AccountOut)
def account(user: User = Depends(current_user)) -> AccountOut:
    """The caller's own account. Requires a session AND an invite."""
    return AccountOut(
        username=user.external_username,
        display_name=user.display_name,
        email=user.email,
        role=user.role,
        role_label=label_for(user.role),
        created_at=user.created_at,
        last_login_at=user.last_login_at,
    )


@router.get("/admin/invites", response_model=list[InviteOut])
def list_invites(
    _admin: User = Depends(current_superadmin),
    db: Session = Depends(get_db),
) -> list[InviteOut]:
    """Every invite, redeemed or not. Super admin only."""
    rows = db.scalars(select(Invite).order_by(Invite.created_at)).all()
    return [
        InviteOut(
            email=r.email,
            role=r.role,
            role_label=label_for(r.role),
            note=r.note,
            created_at=r.created_at,
            redeemed_at=r.redeemed_at,
        )
        for r in rows
    ]
