import re

from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import HTMLResponse, RedirectResponse

from admin.auth import require_admin
from admin.templates_env import templates
from database.queries.org_users import (
    create_org_user,
    delete_org_user,
    get_org_users,
)
from database.queries.organizations import get_all_organizations
import external.client as ext

router = APIRouter(prefix="/org-users", dependencies=[Depends(require_admin)])


def normalize_phone(raw: str) -> str:
    digits = re.sub(r"\D", "", raw)
    if digits.startswith("8") and len(digits) == 11:
        digits = "7" + digits[1:]
    return digits


@router.get("", response_class=HTMLResponse)
async def list_org_users(request: Request, org_id: int | None = None):
    users = await get_org_users(org_id=org_id)
    orgs = await get_all_organizations()
    return templates.TemplateResponse(
        request=request,
        name="org_users/list.html",
        context={"users": users, "orgs": orgs, "filter_org_id": org_id},
    )


@router.get("/create", response_class=HTMLResponse)
async def create_org_user_form(request: Request):
    orgs = await get_all_organizations()
    return templates.TemplateResponse(
        request=request, name="org_users/create.html", context={"orgs": orgs}
    )


@router.post("/create")
async def create_org_user_action(
    org_id: int = Form(...),
    phone: str = Form(...),
    display_name: str = Form(""),
):
    phone = normalize_phone(phone)
    row_id = await create_org_user(
        org_id=org_id,
        phone=phone,
        display_name=display_name or None,
    )
    ext.sync_user(row_id)
    return RedirectResponse("/admin/org-users", status_code=303)


@router.post("/{user_id}/delete")
async def delete_org_user_action(user_id: int):
    await delete_org_user(user_id)
    return RedirectResponse("/admin/org-users", status_code=303)
