import type { BUN_SQLITE_WGUI_CLIENT_ROUTES } from "@/db/types/db"; import adminCrudHandler from "@/src/functions/frontend/admin-crud-handler"; import type { ClientRouteFormInit } from "./types"; import type { ConfirmContextValue } from "../confirm/confirm-context"; type Params = { init: ClientRouteFormInit; host_id: number; cancel_href: string; confirm: ConfirmContextValue["confirm"]; }; export default async function submitClientRouteForm({ init, host_id, cancel_href, confirm, }: Params) { const { form, existing_full, setLoading, setStatus, clearLocalForm } = init; const is_edit = Boolean(existing_full?.id); const confirmed = await confirm( is_edit ? { title: "Save route changes?", message: "Caddy will regenerate its config and reload the TLS ingress.", confirm_label: "Save changes", } : { title: "Create this route?", message: "Caddy will regenerate its config and reload the TLS ingress.", confirm_label: "Create route", }, ); if (!confirmed) return; setLoading(true); try { const data: BUN_SQLITE_WGUI_CLIENT_ROUTES = { host_id, name: form.name || "", hostname: form.hostname || "", path_prefix: form.path_prefix || "/", strip_prefix: form.strip_prefix == 1 ? 1 : 0, upstream_url: form.upstream_url || "", upstream_tls_verify: form.upstream_tls_verify == 0 ? 0 : 1, enabled: form.enabled == 0 ? 0 : 1, notes: form.notes || "", acme_email: form.acme_email || "", acme_staging: form.acme_staging == 1 ? 1 : 0, }; const res = is_edit ? await adminCrudHandler({ action: "update", table: "client_routes", update_data: data, id: existing_full?.id, }) : await adminCrudHandler({ action: "insert", table: "client_routes", insert_data: [data], }); if (!res.success) { throw new Error(res.msg || "Could not save the route"); } const route_id = existing_full?.id || res.postInsertReturn?.insertId || res.singleRes?.id; clearLocalForm(); window.location.href = route_id ? `/admin/hosts/${host_id}/routes/${route_id}` : cancel_href; } catch (error: any) { setStatus({ error: true, msg: error.message || "Could not save the route", }); setLoading(false); } }