"""DM pairing and allowlist API routes."""

from __future__ import annotations

from fastapi import APIRouter, Request
from pydantic import BaseModel

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


class PolicyUpdate(BaseModel):
    policy: str  # pairing | allowlist | open


class PairingAction(BaseModel):
    channel: str
    sender_id: str


@router.get("/dm-policy")
async def get_dm_policy(request: Request) -> dict:
    pairing = request.app.state.pairing
    return {"policy": await pairing.get_dm_policy()}


@router.put("/dm-policy")
async def set_dm_policy(request: Request, body: PolicyUpdate) -> dict:
    if body.policy not in ("pairing", "allowlist", "open"):
        return {"error": "Invalid policy. Must be: pairing, allowlist, or open"}
    pairing = request.app.state.pairing
    await pairing.set_dm_policy(body.policy)
    return {"policy": body.policy}


@router.get("/pairing/pending")
async def get_pending_pairings(request: Request) -> list[dict]:
    pairing = request.app.state.pairing
    return await pairing.get_pending()


@router.post("/pairing/approve")
async def approve_pairing(request: Request, body: PairingAction) -> dict:
    pairing = request.app.state.pairing
    ok = await pairing.approve(body.channel, body.sender_id)
    return {"approved": ok}


@router.post("/pairing/reject")
async def reject_pairing(request: Request, body: PairingAction) -> dict:
    pairing = request.app.state.pairing
    ok = await pairing.reject(body.channel, body.sender_id)
    return {"rejected": ok}


@router.get("/allowlist")
async def get_allowlist(request: Request) -> list[dict]:
    pairing = request.app.state.pairing
    return await pairing.get_allowlist()


@router.post("/allowlist")
async def add_to_allowlist(request: Request, body: PairingAction) -> dict:
    pairing = request.app.state.pairing
    await pairing.add_to_allowlist(body.channel, body.sender_id)
    return {"added": True}


@router.delete("/allowlist")
async def remove_from_allowlist(request: Request, body: PairingAction) -> dict:
    pairing = request.app.state.pairing
    await pairing.remove_from_allowlist(body.channel, body.sender_id)
    return {"removed": True}
