"use server";

import { revalidatePath } from "next/cache";
import { api } from "../../../convex/_generated/api";
import { m } from "@/lib/convex-server";
import { run, type ActionResult } from "@/lib/action";
import type { AppSettings } from "@/lib/settings-defaults";

export async function updateSettings(patch: Partial<AppSettings>, group = "general"): Promise<ActionResult<undefined>> {
  return run(async () => {
    await m(api.settings.update, { patch, group });
    revalidatePath("/", "layout");
    return undefined;
  });
}

export async function updateNotificationRule(eventType: string, patch: { enabled?: boolean; inApp?: boolean; email?: boolean; push?: boolean; priority?: string; recipientRoles?: string[]; recipientUserIds?: string[]; recipientRoleId?: string | null; recipientUserId?: string | null; notifyActor?: boolean; notifyAssigned?: boolean }): Promise<ActionResult<undefined>> {
  return run(async () => {
    const { recipientRoleId, recipientUserId, ...rest } = patch;
    const p: Record<string, unknown> = { ...rest };
    if (recipientRoleId !== undefined) p.recipientRoles = recipientRoleId ? [recipientRoleId] : [];
    if (recipientUserId !== undefined) p.recipientUserIds = recipientUserId ? [recipientUserId] : [];
    await m(api.settings.updateRule, { eventType, patch: p });
    revalidatePath("/settings/notifications");
    return undefined;
  });
}

export async function markNotificationsRead(ids: string[] | "all"): Promise<ActionResult<undefined>> {
  return run(async () => {
    await m(api.settings.markRead, { ids: ids === "all" ? undefined : ids });
    revalidatePath("/notifications");
    return undefined;
  });
}
