import type { Group, GroupRole } from "~/types"; export function useGroupsApi() { const { needLogin } = useAuthState(); const groups = ref([]); const isSuper = ref(false); /** groupId → role of the signed-in user (absent for super admins). */ const roles = ref>({}); const loading = ref(false); const error = ref(""); function roleOf(groupId: string): GroupRole | undefined { return isSuper.value ? "owner" : roles.value[groupId]; } function canEditGroup(groupId: string): boolean { const r = roleOf(groupId); return isSuper.value || r === "owner"; } function canEditRoutes(groupId: string): boolean { const r = roleOf(groupId); return isSuper.value || r === "owner" || r === "admin"; } async function load(): Promise { loading.value = true; error.value = ""; needLogin.value = false; try { const data = await apiFetch<{ groups?: Group[]; isSuper?: boolean; roles?: Record; }>("/admin/api/groups"); groups.value = data.groups ?? []; isSuper.value = data.isSuper ?? false; roles.value = data.roles ?? {}; } catch (err) { if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err); } finally { loading.value = false; } } async function save(next: Group[]): Promise { await apiFetch("/admin/api/groups", { method: "PUT", body: JSON.stringify({ groups: next }), }); groups.value = next; } /** Rename a group; routes, webhook secret and invites follow automatically. */ async function rename(oldId: string, newId: string): Promise { await apiFetch(`/admin/api/groups/${encodeURIComponent(oldId)}/rename`, { method: "PUT", body: JSON.stringify({ newId }), }); } return { groups, isSuper, roles, roleOf, canEditGroup, canEditRoutes, loading, needLogin, error, load, save, rename, }; }