"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
import { requireProfile } from "@/lib/auth";
import { createServerSupabaseClient } from "@/lib/supabase/server";
import { writeAuditLog } from "@/lib/audit";

function target(result: "success" | "error", message: string) {
  return `/donor/profile?${result}=${encodeURIComponent(message)}`;
}

export async function updateDonorProfileAction(formData: FormData) {
  const parsed = z
    .object({
      fullName: z.string().trim().min(3).max(120)
    })
    .safeParse({ fullName: formData.get("fullName") });
  if (!parsed.success) redirect(target("error", "تحقق من الاسم الكامل"));

  const profile = await requireProfile("donor");
  const supabase = await createServerSupabaseClient();
  const { error } = await supabase
    .from("profiles")
    .update({ full_name: parsed.data.fullName })
    .eq("id", profile.id);
  if (error) redirect(target("error", "تعذر تحديث الملف الشخصي"));
  await writeAuditLog({ actorId: profile.id, action: "profile.updated", entityType: "profile", entityId: profile.id });
  revalidatePath("/donor", "layout");
  redirect(target("success", "تم تحديث الملف الشخصي"));
}

export async function markNotificationReadAction(formData: FormData) {
  const id = String(formData.get("id") ?? "");
  if (!z.uuid().safeParse(id).success) return;
  const profile = await requireProfile("donor");
  const supabase = await createServerSupabaseClient();
  await supabase.from("notifications").update({ read_at: new Date().toISOString() }).eq("id", id).eq("recipient_id", profile.id);
  revalidatePath("/donor/notifications");
}
