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.organizations import (
    create_organization,
    delete_organization,
    get_all_organizations,
    get_organization,
    update_organization,
)
import external.client as ext

router = APIRouter(prefix="/orgs", dependencies=[Depends(require_admin)])


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


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


@router.post("/create")
async def create_org(name: str = Form(...)):
    org_id = await create_organization(name)
    ext.sync_org(org_id)
    return RedirectResponse("/admin/orgs", status_code=303)


@router.get("/{org_id}/edit", response_class=HTMLResponse)
async def edit_org_form(request: Request, org_id: int):
    org = await get_organization(org_id)
    return templates.TemplateResponse(
        request=request, name="orgs/edit.html", context={"org": org}
    )


@router.post("/{org_id}/edit")
async def edit_org(org_id: int, name: str = Form(...)):
    await update_organization(org_id, name)
    return RedirectResponse("/admin/orgs", status_code=303)


@router.post("/{org_id}/delete")
async def delete_org(org_id: int):
    await delete_organization(org_id)
    return RedirectResponse("/admin/orgs", status_code=303)
