"use server";

import { randomUUID } from "node:crypto";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
import { writeAuditLog } from "@/lib/audit";
import { requireProfile } from "@/lib/auth";
import { orphanDocumentLabels } from "@/lib/constants";
import { todayIso } from "@/lib/dates";
import type { OrphanUploadIdentity } from "@/lib/orphan-upload-path";
import {
  ensurePendingOrphanUploadFolders,
  finalizePendingOrphanUploads,
  movePrivateUploadByReference,
  removeOrphanUploadTree,
  removePendingOrphanUploadTree,
  removePrivateUpload,
  removePrivateUploadByReference,
  renameOrphanUploadTree,
  savePendingPrivateUpload,
  savePrivateUpload,
  type StoredPrivateFile
} from "@/lib/storage";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
import { sponsorPhoneIdentity } from "@/lib/sponsor-account";
import {
  orphanDocumentTypeSchema,
  orphanSchema,
  orphanTransferSchema,
  passwordResetSchema,
  sponsorMonthlyPaymentSchema,
  sponsorSchema,
  sponsorUpdateSchema,
  sponsorshipSchema,
  sponsorshipUpdateSchema
} from "@/lib/validation";
import { asNumber, nonEmpty } from "@/lib/utils";

function target(path: string, result: "success" | "error", message: string) {
  const separator = path.includes("?") ? "&" : "?";
  return `${path}${separator}${result}=${encodeURIComponent(message)}`;
}

function returnPath(formData: FormData, fallback: string) {
  const value = String(formData.get("returnTo") ?? "");
  return value.startsWith("/admin/") && !value.startsWith("//") ? value : fallback;
}

async function adminContext() {
  const profile = await requireProfile("admin");
  return { profile, supabase: createAdminSupabaseClient() };
}

async function orphanUploadIdentity(
  supabase: ReturnType<typeof createAdminSupabaseClient>,
  orphanId: string
): Promise<OrphanUploadIdentity> {
  const { data: orphan, error } = await supabase
    .from("orphans")
    .select("id,full_name,case_number")
    .eq("id", orphanId)
    .maybeSingle();
  if (error || !orphan) throw new Error("تعذر العثور على مجلد ملفات اليتيم");
  return {
    orphanId: orphan.id,
    orphanName: orphan.full_name ?? "يتيم",
    caseNumber: orphan.case_number
  };
}

async function activeSponsorOrphanLinkExists(
  supabase: ReturnType<typeof createAdminSupabaseClient>,
  sponsorId: string,
  orphanId: string
): Promise<boolean> {
  const { data, error } = await supabase
    .from("sponsorships")
    .select("id")
    .eq("donor_id", sponsorId)
    .eq("orphan_id", orphanId)
    .eq("status", "active")
    .limit(1)
    .maybeSingle();
  if (error) throw new Error("تعذر التحقق من علاقة الكفالة");
  return Boolean(data);
}

function orphanInput(formData: FormData) {
  return {
    fullName: formData.get("fullName"),
    dateOfBirth: formData.get("dateOfBirth"),
    gender: formData.get("gender"),
    sponsorNotes: formData.get("sponsorNotes"),
    privateNotes: formData.get("privateNotes"),
    guardianName: formData.get("guardianName"),
    guardianPhone: formData.get("guardianPhone"),
    guardianRelationship: formData.get("guardianRelationship"),
    address: formData.get("address"),
    bankName: formData.get("bankName"),
    bankAccountName: formData.get("bankAccountName"),
    bankAccountNumber: formData.get("bankAccountNumber"),
    monthlyNeed: formData.get("monthlyNeed"),
    status: formData.get("status") || undefined
  };
}

const documentInputs = [
  { field: "orphanNationalId", type: "orphan_national_id" },
  { field: "fatherDeathCertificate", type: "father_death_certificate" },
  { field: "guardianNationalId", type: "guardian_national_id" }
] as const;

function normalizedIdentifier(value: string | null | undefined) {
  return value?.normalize("NFKC").trim().toLocaleLowerCase("ar").replace(/[\s\p{P}\p{S}]+/gu, "") ?? "";
}

function digits(value: string | null | undefined) {
  return value?.replace(/\D/g, "") ?? "";
}

type DuplicateMatch = {
  id: string;
  case_number: string;
  full_name: string | null;
  date_of_birth: string | null;
  guardian_name: string | null;
  guardian_phone: string | null;
  bank_account_number: string | null;
};

async function findDuplicateOrphans(
  supabase: ReturnType<typeof createAdminSupabaseClient>,
  values: z.infer<typeof orphanSchema>,
  files: Array<{ type: (typeof documentInputs)[number]["type"]; stored: StoredPrivateFile }>
): Promise<DuplicateMatch[]> {
  const name = normalizedIdentifier(values.fullName);
  const guardian = normalizedIdentifier(values.guardianName);
  const phone = digits(values.guardianPhone);
  const bank = normalizedIdentifier(values.bankAccountNumber);
  const matched = new Map<string, DuplicateMatch>();
  const filters: string[] = [];
  if (name && values.dateOfBirth) filters.push(`and(normalized_full_name.eq.${name},date_of_birth.eq.${values.dateOfBirth})`);
  if (name && phone) filters.push(`and(normalized_full_name.eq.${name},normalized_guardian_phone.eq.${phone})`);
  if (guardian && phone) filters.push(`and(normalized_guardian_name.eq.${guardian},normalized_guardian_phone.eq.${phone})`);
  if (bank) filters.push(`normalized_bank_account_number.eq.${bank}`);
  const { data: candidates } = filters.length
    ? await supabase
        .from("orphans")
        .select("id,case_number,full_name,date_of_birth,guardian_name,guardian_phone,bank_account_number")
        .or(filters.join(","))
        .limit(100)
    : { data: [] };

  for (const candidate of candidates ?? []) {
    const candidateName = normalizedIdentifier(candidate.full_name);
    const candidateGuardian = normalizedIdentifier(candidate.guardian_name);
    const candidatePhone = digits(candidate.guardian_phone);
    const candidateBank = normalizedIdentifier(candidate.bank_account_number);
    const sameNameBirth =
      Boolean(name && values.dateOfBirth) &&
      candidateName === name &&
      candidate.date_of_birth === values.dateOfBirth;
    const sameNamePhone = Boolean(name && phone) && candidateName === name && candidatePhone === phone;
    const sameGuardianPhone =
      Boolean(guardian && phone) &&
      candidateGuardian === guardian &&
      candidatePhone === phone;
    const sameBank = Boolean(bank) && candidateBank === bank;
    if (sameNameBirth || sameNamePhone || sameGuardianPhone || sameBank) matched.set(candidate.id, candidate);
  }

  const identityHashes = files
    .filter((item) => item.type === "orphan_national_id" || item.type === "guardian_national_id")
    .map((item) => item.stored.sha256);
  if (identityHashes.length) {
    const { data: assets } = await supabase
      .from("file_assets")
      .select("id")
      .in("sha256", identityHashes)
      .in("category", ["orphan_national_id", "guardian_national_id"]);
    const fileIds = (assets ?? []).map((asset) => asset.id);
    if (fileIds.length) {
      const { data: documents } = await supabase
        .from("orphan_documents")
        .select("orphan_id")
        .in("file_id", fileIds);
      const orphanIds = [...new Set((documents ?? []).map((document) => document.orphan_id))];
      if (orphanIds.length) {
        const { data: fileMatches } = await supabase
          .from("orphans")
          .select("id,case_number,full_name,date_of_birth,guardian_name,guardian_phone,bank_account_number")
          .in("id", orphanIds);
        for (const candidate of fileMatches ?? []) matched.set(candidate.id, candidate);
      }
    }
  }

  return [...matched.values()].slice(0, 10);
}

export async function createOrphanAction(formData: FormData) {
  const parsed = orphanSchema.safeParse(orphanInput(formData));
  if (!parsed.success) {
    redirect(target("/admin/orphans/new", "error", parsed.error.issues[0]?.message ?? "بيانات الحالة غير صحيحة"));
  }

  const { profile, supabase } = await adminContext();
  const storedFiles: Array<{ type: (typeof documentInputs)[number]["type"]; stored: StoredPrivateFile }> = [];
  const createdOrphanId = randomUUID();
  let generatedCaseNumber = "";
  let duplicateMatches: DuplicateMatch[] = [];
  let finalUploadIdentity: OrphanUploadIdentity | null = null;
  let createdInDatabase = false;
  let uploadsFinalized = false;

  try {
    await ensurePendingOrphanUploadFolders(createdOrphanId);
    for (const item of documentInputs) {
      const file = formData.get(item.field);
      if (!(file instanceof File) || file.size <= 0) continue;
      storedFiles.push({
        type: item.type,
        stored: await savePendingPrivateUpload(file, {
          orphanId: createdOrphanId,
          kind: "documents",
          imageOnly: true
        })
      });
    }

    duplicateMatches = await findDuplicateOrphans(supabase, parsed.data, storedFiles);
  } catch (error) {
    await removePendingOrphanUploadTree(createdOrphanId);
    redirect(target("/admin/orphans/new", "error", error instanceof Error ? error.message : "تعذر فحص الملفات"));
  }

  const override = formData.get("duplicateOverride") === "true";
  if (duplicateMatches.length && !override) {
    await removePendingOrphanUploadTree(createdOrphanId);
    const ids = duplicateMatches.map((item) => item.id).join(",");
    redirect(
      `/admin/orphans/new?duplicates=${encodeURIComponent(ids)}&error=${encodeURIComponent(
        "قد تكون هذه الحالة مضافة مسبقاً."
      )}`
    );
  }

  try {
    const value = parsed.data;
    const { data, error } = await supabase.rpc("create_orphan_with_documents_v2", {
      p_orphan_id: createdOrphanId,
      p_full_name: value.fullName,
      p_date_of_birth: value.dateOfBirth,
      p_gender: value.gender,
      p_guardian_name: value.guardianName,
      p_guardian_phone: value.guardianPhone,
      p_guardian_relationship: value.guardianRelationship,
      p_address: value.address,
      p_bank_name: value.bankName,
      p_bank_account_name: value.bankAccountName,
      p_bank_account_number: value.bankAccountNumber,
      p_monthly_need: value.monthlyNeed,
      p_sponsor_notes: value.sponsorNotes,
      p_private_notes: value.privateNotes,
      p_created_by: profile.id,
      p_documents: storedFiles.map(({ type, stored }) => ({
        document_type: type,
        title: orphanDocumentLabels[type],
        stored_name: stored.storedName,
        original_name: stored.originalName,
        extension: stored.extension,
        mime_type: stored.mimeType,
        size_bytes: stored.sizeBytes,
        sha256: stored.sha256
      }))
    });
    if (error) throw error;

    const created = Array.isArray(data) ? data[0] : data;
    if (!created?.orphan_id || !created.generated_case_number) throw new Error("تعذر إنشاء سجل الحالة");
    generatedCaseNumber = created.generated_case_number;
    createdInDatabase = true;
    const createdUploadIdentity: OrphanUploadIdentity = {
      orphanId: createdOrphanId,
      orphanName: value.fullName ?? "يتيم",
      caseNumber: generatedCaseNumber
    };
    finalUploadIdentity = createdUploadIdentity;
    await finalizePendingOrphanUploads(createdOrphanId, createdUploadIdentity);
    uploadsFinalized = true;
    await writeAuditLog({
      actorId: profile.id,
      action: duplicateMatches.length ? "orphan.created_duplicate_override" : "orphan.created",
      entityType: "orphan",
      entityId: createdOrphanId,
      metadata: {
        caseNumber: generatedCaseNumber,
        documents: storedFiles.map((item) => item.type),
        duplicateOverride: duplicateMatches.length > 0,
        possibleDuplicateCaseIds: duplicateMatches.map((item) => item.id)
      }
    });
  } catch (error) {
    await removePendingOrphanUploadTree(createdOrphanId);
    if (uploadsFinalized && finalUploadIdentity) await removeOrphanUploadTree(finalUploadIdentity);
    if (createdInDatabase && generatedCaseNumber) {
      await supabase.rpc("delete_orphan_complete", {
        p_orphan_id: createdOrphanId,
        p_case_number: generatedCaseNumber,
        p_actor: profile.id
      });
    }
    redirect(
      target(
        "/admin/orphans/new",
        "error",
        error instanceof Error ? error.message : "تعذر إنشاء الحالة"
      )
    );
  }

  revalidatePath("/admin/orphans");
  redirect(target(`/admin/orphans/${createdOrphanId}`, "success", `تم إنشاء الحالة ${generatedCaseNumber}`));
}

export async function updateOrphanAction(formData: FormData) {
  const id = String(formData.get("id") ?? "");
  const parsed = orphanSchema.safeParse(orphanInput(formData));
  if (!z.uuid().safeParse(id).success || !parsed.success) {
    redirect(
      target(
        `/admin/orphans/${id}`,
        "error",
        parsed.success ? "الحالة غير صحيحة" : parsed.error.issues[0]?.message ?? "بيانات غير صحيحة"
      )
    );
  }

  const { profile, supabase } = await adminContext();
  const value = parsed.data;
  const previousUploadIdentity = await orphanUploadIdentity(supabase, id).catch(() =>
    redirect(target(`/admin/orphans/${id}`, "error", "تعذر العثور على مجلد ملفات اليتيم"))
  );
  const nextUploadIdentity: OrphanUploadIdentity = {
    ...previousUploadIdentity,
    orphanName: value.fullName ?? "يتيم"
  };
  try {
    await renameOrphanUploadTree(previousUploadIdentity, nextUploadIdentity);
  } catch {
    redirect(target(`/admin/orphans/${id}`, "error", "تعذر إعادة تسمية مجلد ملفات اليتيم"));
  }

  const { error } = await supabase
    .from("orphans")
    .update({
      full_name: value.fullName,
      date_of_birth: value.dateOfBirth,
      gender: value.gender,
      sponsor_notes: value.sponsorNotes,
      private_notes: value.privateNotes,
      guardian_name: value.guardianName,
      guardian_phone: value.guardianPhone,
      guardian_relationship: value.guardianRelationship,
      address: value.address,
      bank_name: value.bankName,
      bank_account_name: value.bankAccountName,
      bank_account_number: value.bankAccountNumber,
      monthly_need: value.monthlyNeed,
      status: value.status
    })
    .eq("id", id);
  if (error) {
    await renameOrphanUploadTree(nextUploadIdentity, previousUploadIdentity).catch(() => undefined);
    redirect(target(`/admin/orphans/${id}`, "error", "تعذر تحديث الحالة"));
  }

  await writeAuditLog({
    actorId: profile.id,
    action: "orphan.updated",
    entityType: "orphan",
    entityId: id,
    metadata: { status: value.status }
  });
  revalidatePath("/admin/orphans", "layout");
  revalidatePath("/donor", "layout");
  redirect(target(`/admin/orphans/${id}`, "success", "تم تحديث بيانات الحالة"));
}

export async function deleteOrphanAction(formData: FormData) {
  const id = String(formData.get("id") ?? "");
  const caseConfirmation = String(formData.get("caseConfirmation") ?? "").trim();
  if (!z.uuid().safeParse(id).success || !/^ORP-\d{6,}$/.test(caseConfirmation)) {
    redirect(target(`/admin/orphans/${id}`, "error", "رقم الحالة المكتوب غير صحيح"));
  }

  const { profile, supabase } = await adminContext();
  const uploadIdentity = await orphanUploadIdentity(supabase, id).catch(() =>
    redirect(target(`/admin/orphans/${id}`, "error", "تعذر العثور على مجلد ملفات اليتيم"))
  );
  const { data, error } = await supabase.rpc("delete_orphan_complete", {
    p_orphan_id: id,
    p_case_number: caseConfirmation,
    p_actor: profile.id
  });
  if (error) {
    const message = error.message.includes("confirmation")
      ? "رقم الحالة المكتوب لا يطابق الملف"
      : "تعذر حذف ملف الحالة. لم يكتمل الحذف.";
    redirect(target(`/admin/orphans/${id}`, "error", message));
  }

  const result = Array.isArray(data) ? data[0] : data;
  const files = Array.isArray(result?.removed_files)
    ? (result.removed_files as Array<{ stored_name: string; extension: string }>)
    : [];
  const failed: string[] = [];
  if (!(await removeOrphanUploadTree(uploadIdentity))) failed.push(`orphans/${uploadIdentity.orphanName}`);
  for (const file of files) {
    if (!(await removePrivateUploadByReference(uploadIdentity, file.stored_name, file.extension))) {
      failed.push(`${file.stored_name}.${file.extension}`);
    }
  }

  await writeAuditLog({
    actorId: profile.id,
    action: failed.length ? "orphan.deleted_file_cleanup_pending" : "orphan.deleted",
    entityType: "orphan_deleted",
    metadata: {
      caseNumber: result?.deleted_case_number ?? caseConfirmation,
      displayName: result?.deleted_full_name ?? null,
      removedFileCount: files.length,
      failedFileCleanupCount: failed.length
    }
  });
  revalidatePath("/admin", "layout");
  const message = failed.length
    ? `حذف سجل الحالة، لكن تعذر حذف ${failed.length} ملف من القرص. راجع سجل التدقيق.`
    : `تم حذف ملف الحالة ${caseConfirmation} بالكامل`;
  redirect(target("/admin/orphans", failed.length ? "error" : "success", message));
}

export async function createSponsorAction(formData: FormData) {
  const parsed = sponsorSchema.safeParse({
    fullName: formData.get("fullName"),
    phone: formData.get("phone"),
    password: formData.get("password"),
    isActive: formData.get("isActive") === "on"
  });
  if (!parsed.success) {
    redirect(target("/admin/donors", "error", parsed.error.issues[0]?.message ?? "بيانات المتبرع غير صحيحة"));
  }

  const { profile, supabase } = await adminContext();
  const value = parsed.data;
  const identity = sponsorPhoneIdentity(value.phone);
  if (!identity) {
    redirect(target("/admin/donors", "error", "رقم هاتف المتبرع غير مدعوم"));
  }
  const created = await supabase.auth.admin.createUser({
    phone: value.phone,
    password: value.password,
    phone_confirm: true,
    user_metadata: {
      full_name: value.fullName,
      phone: value.phone,
      login_username: identity.loginUsername,
      initial_role: "donor",
      must_change_password: true
    }
  });
  if (created.error || !created.data.user) {
    redirect(target("/admin/donors", "error", "تعذر إنشاء الحساب. تحقق من أن رقم الهاتف غير مستخدم."));
  }

  const userId = created.data.user.id;
  const { error: profileError } = await supabase.from("profiles").upsert({
    id: userId,
    role: "donor",
    full_name: value.fullName,
    phone: value.phone,
    login_username: identity.loginUsername,
    must_change_password: true,
    is_active: value.isActive
  });
  if (profileError) {
    await supabase.auth.admin.deleteUser(userId);
    redirect(target("/admin/donors", "error", "تعذر إنشاء ملف المتبرع، وتم التراجع عن حساب الدخول."));
  }

  if (!value.isActive) {
    const disabled = await supabase.auth.admin.updateUserById(userId, { ban_duration: "876000h" });
    if (disabled.error) {
      await supabase.auth.admin.deleteUser(userId);
      redirect(target("/admin/donors", "error", "تعذر إنشاء الحساب بحالة موقوفة."));
    }
  }

  await writeAuditLog({
    actorId: profile.id,
    action: "sponsor.created",
    entityType: "profile",
    entityId: userId,
    metadata: { active: value.isActive }
  });
  revalidatePath("/admin/donors");
  redirect(target(`/admin/donors/${userId}`, "success", "تم إنشاء حساب المتبرع وتأكيد رقم الهاتف"));
}

export async function updateSponsorAction(formData: FormData) {
  const parsed = sponsorUpdateSchema.safeParse({
    id: formData.get("id"),
    fullName: formData.get("fullName"),
    phone: formData.get("phone")
  });
  const fallback = `/admin/donors/${String(formData.get("id") ?? "")}`;
  if (!parsed.success) {
    redirect(target(fallback, "error", parsed.error.issues[0]?.message ?? "بيانات المتبرع غير صحيحة"));
  }

  const { profile, supabase } = await adminContext();
  const identity = sponsorPhoneIdentity(parsed.data.phone);
  if (!identity) redirect(target(fallback, "error", "رقم هاتف المتبرع غير مدعوم"));
  const { data: previous } = await supabase
    .from("profiles")
    .select("full_name,phone,login_username,must_change_password,deleted_at")
    .eq("id", parsed.data.id)
    .eq("role", "donor")
    .maybeSingle();
  if (!previous) redirect(target(fallback, "error", "حساب المتبرع غير موجود"));
  if (previous.deleted_at) redirect(target("/admin/donors", "error", "حساب المتبرع محذوف"));

  const authUpdate = await supabase.auth.admin.updateUserById(parsed.data.id, {
    phone: parsed.data.phone,
    phone_confirm: true,
    user_metadata: {
      full_name: parsed.data.fullName,
      phone: parsed.data.phone,
      login_username: identity.loginUsername,
      initial_role: "donor",
      must_change_password: previous.must_change_password
    }
  });
  if (authUpdate.error) redirect(target(fallback, "error", "تعذر تحديث رقم الدخول. قد يكون الرقم مستخدماً."));

  const { error } = await supabase
    .from("profiles")
    .update({
      full_name: parsed.data.fullName,
      phone: parsed.data.phone,
      login_username: identity.loginUsername
    })
    .eq("id", parsed.data.id)
    .eq("role", "donor");
  if (error) {
    await supabase.auth.admin.updateUserById(parsed.data.id, {
      phone: previous.phone ?? undefined,
      phone_confirm: true,
      user_metadata: {
        full_name: previous.full_name,
        phone: previous.phone,
        login_username: previous.login_username,
        initial_role: "donor",
        must_change_password: previous.must_change_password
      }
    });
    redirect(target(fallback, "error", "تعذر تحديث ملف المتبرع"));
  }

  await writeAuditLog({
    actorId: profile.id,
    action: "sponsor.updated",
    entityType: "profile",
    entityId: parsed.data.id
  });
  revalidatePath("/admin/donors", "layout");
  redirect(target(fallback, "success", "تم تحديث بيانات المتبرع"));
}

export async function setSponsorStatusAction(formData: FormData) {
  const id = String(formData.get("id") ?? "");
  const active = formData.get("active") === "true";
  const fallback = `/admin/donors/${id}`;
  if (!z.uuid().safeParse(id).success) redirect(target("/admin/donors", "error", "حساب المتبرع غير صحيح"));

  const { profile, supabase } = await adminContext();
  const { data: account } = await supabase
    .from("profiles")
    .select("deleted_at")
    .eq("id", id)
    .eq("role", "donor")
    .maybeSingle();
  if (!account || account.deleted_at) {
    redirect(target("/admin/donors", "error", "حساب المتبرع غير موجود أو محذوف"));
  }

  const authUpdate = await supabase.auth.admin.updateUserById(id, {
    ban_duration: active ? "none" : "876000h"
  });
  if (authUpdate.error) redirect(target(fallback, "error", "تعذر تحديث حالة حساب الدخول"));

  const { error } = await supabase.from("profiles").update({ is_active: active }).eq("id", id).eq("role", "donor");
  if (error) {
    await supabase.auth.admin.updateUserById(id, { ban_duration: active ? "876000h" : "none" });
    redirect(target(fallback, "error", "تعذر تحديث حالة ملف المتبرع"));
  }

  await writeAuditLog({
    actorId: profile.id,
    action: active ? "sponsor.activated" : "sponsor.deactivated",
    entityType: "profile",
    entityId: id
  });
  revalidatePath("/admin/donors", "layout");
  redirect(target(fallback, "success", active ? "تم تفعيل حساب المتبرع" : "تم إيقاف حساب المتبرع"));
}

export async function deleteSponsorAccountAction(formData: FormData) {
  const id = String(formData.get("id") ?? "");
  if (!z.uuid().safeParse(id).success) {
    redirect(target("/admin/donors", "error", "حساب المتبرع غير صحيح"));
  }

  const { profile, supabase } = await adminContext();
  const { data: account, error: accountError } = await supabase
    .from("profiles")
    .select("id,full_name,is_active,deleted_at")
    .eq("id", id)
    .eq("role", "donor")
    .maybeSingle();
  if (accountError || !account) {
    redirect(target("/admin/donors", "error", "حساب المتبرع غير موجود"));
  }
  if (account.deleted_at) {
    redirect(target("/admin/donors", "success", "حساب المتبرع محذوف بالفعل"));
  }

  const disabled = await supabase.auth.admin.updateUserById(id, {
    ban_duration: "876000h"
  });
  if (disabled.error) {
    redirect(target(`/admin/donors/${id}`, "error", "تعذر إيقاف حساب تسجيل الدخول"));
  }

  const deletedAt = new Date().toISOString();
  const { data: tombstone, error: profileError } = await supabase
    .from("profiles")
    .update({
      is_active: false,
      deleted_at: deletedAt
    })
    .eq("id", id)
    .eq("role", "donor")
    .is("deleted_at", null)
    .select("id")
    .maybeSingle();
  if (profileError || !tombstone) {
    await supabase.auth.admin.updateUserById(id, {
      ban_duration: account.is_active ? "none" : "876000h"
    });
    redirect(target(`/admin/donors/${id}`, "error", "تعذر حذف حساب المتبرع"));
  }

  await writeAuditLog({
    actorId: profile.id,
    action: "sponsor.account_deleted",
    entityType: "profile",
    entityId: id,
    metadata: {
      recordsPreserved: true
    }
  });
  revalidatePath("/admin", "layout");
  redirect(target("/admin/donors", "success", `تم حذف حساب ${account.full_name} مع الاحتفاظ بجميع السجلات المرتبطة به`));
}

export async function resetAccountPasswordAction(formData: FormData) {
  const parsed = passwordResetSchema.safeParse({
    id: formData.get("id"),
    password: formData.get("password"),
    confirmation: formData.get("confirmation")
  });
  const fallback = returnPath(formData, "/admin/settings");
  if (!parsed.success) {
    redirect(target(fallback, "error", parsed.error.issues[0]?.message ?? "كلمة المرور غير صحيحة"));
  }

  const { profile, supabase } = await adminContext();
  const { data: account, error: accountError } = await supabase
    .from("profiles")
    .select("id,role,full_name,deleted_at")
    .eq("id", parsed.data.id)
    .maybeSingle();
  if (accountError || !account) {
    redirect(target(fallback, "error", "الحساب غير موجود"));
  }
  if (account.deleted_at) {
    redirect(target("/admin/settings", "error", "الحساب محذوف ولا يمكن إعادة تعيين كلمة مروره"));
  }

  const { error } = await supabase.auth.admin.updateUserById(parsed.data.id, {
    password: parsed.data.password
  });
  if (error) redirect(target(fallback, "error", "تعذر إعادة تعيين كلمة المرور"));

  await writeAuditLog({
    actorId: profile.id,
    action: "account.password_reset",
    entityType: "profile",
    entityId: parsed.data.id,
    metadata: {
      targetRole: account.role
    }
  });
  revalidatePath("/admin", "layout");
  redirect(target(fallback, "success", `تم تعيين كلمة مرور جديدة لحساب ${account.full_name}. لن تعرضها المنصة مرة أخرى.`));
}

export async function createSponsorshipAction(formData: FormData) {
  const parsed = sponsorshipSchema.safeParse({
    donorId: formData.get("donorId"),
    orphanId: formData.get("orphanId"),
    monthlyAmount: formData.get("monthlyAmount"),
    startDate: formData.get("startDate"),
    notes: formData.get("notes")
  });
  const destination = returnPath(formData, "/admin/sponsorships");
  if (!parsed.success) {
    redirect(target(destination, "error", parsed.error.issues[0]?.message ?? "بيانات الكفالة غير صحيحة"));
  }

  const { profile, supabase } = await adminContext();
  const { data, error } = await supabase
    .from("sponsorships")
    .insert({
      donor_id: parsed.data.donorId,
      orphan_id: parsed.data.orphanId,
      monthly_amount: parsed.data.monthlyAmount,
      start_date: parsed.data.startDate,
      status: "active",
      notes: parsed.data.notes,
      created_by: profile.id
    })
    .select("id")
    .single();
  if (error) redirect(target(destination, "error", "تعذر إنشاء الكفالة. قد توجد علاقة نشطة بالفعل."));

  await writeAuditLog({
    actorId: profile.id,
    action: "sponsorship.created",
    entityType: "sponsorship",
    entityId: data.id,
    metadata: {
      orphanId: parsed.data.orphanId,
      sponsorId: parsed.data.donorId,
      monthlyAmount: parsed.data.monthlyAmount
    }
  });
  revalidatePath("/admin", "layout");
  redirect(target(destination, "success", "تم ربط المتبرع بالحالة"));
}

export async function updateSponsorshipAction(formData: FormData) {
  const parsed = sponsorshipUpdateSchema.safeParse({
    id: formData.get("id"),
    monthlyAmount: formData.get("monthlyAmount"),
    status: formData.get("status"),
    endDate: formData.get("endDate") || "",
    stopReason: formData.get("stopReason"),
    notes: formData.get("notes")
  });
  const destination = returnPath(formData, "/admin/sponsorships");
  if (!parsed.success) {
    redirect(target(destination, "error", parsed.error.issues[0]?.message ?? "بيانات العلاقة غير صحيحة"));
  }

  const { profile, supabase } = await adminContext();
  const { data: previous } = await supabase
    .from("sponsorships")
    .select("monthly_amount,status,end_date,stop_reason,notes")
    .eq("id", parsed.data.id)
    .maybeSingle();
  const ended = parsed.data.status === "ended";
  const { error } = await supabase
    .from("sponsorships")
    .update({
      monthly_amount: parsed.data.monthlyAmount,
      status: parsed.data.status,
      end_date: ended ? parsed.data.endDate || todayIso() : null,
      stop_reason: ended ? parsed.data.stopReason : null,
      notes: parsed.data.notes
    })
    .eq("id", parsed.data.id);
  if (error) redirect(target(destination, "error", "تعذر تحديث علاقة الكفالة"));

  await writeAuditLog({
    actorId: profile.id,
    action: ended ? "sponsorship.ended" : "sponsorship.updated",
    entityType: "sponsorship",
    entityId: parsed.data.id,
    metadata: {
      before: previous,
      after: { status: parsed.data.status, monthlyAmount: parsed.data.monthlyAmount }
    }
  });
  revalidatePath("/admin", "layout");
  revalidatePath("/donor", "layout");
  redirect(target(destination, "success", ended ? "تم إنهاء العلاقة مع حفظ تاريخها" : "تم تحديث علاقة الكفالة"));
}

export async function generateSponsorPaymentsAction(formData: FormData) {
  const year = Number(formData.get("year"));
  const month = Number(formData.get("month"));
  const destination = returnPath(formData, "/admin/payments");
  if (!Number.isInteger(year) || year < 2020 || year > 2200 || !Number.isInteger(month) || month < 1 || month > 12) {
    redirect(target(destination, "error", "الفترة الشهرية غير صحيحة"));
  }

  const { profile, supabase } = await adminContext();
  const { data, error } = await supabase.rpc("ensure_sponsor_monthly_payments", {
    target_year: year,
    target_month: month,
    actor: profile.id
  });
  if (error) redirect(target(destination, "error", "تعذر إنشاء التزامات المتبرعين الشهرية"));
  await writeAuditLog({
    actorId: profile.id,
    action: "sponsor_monthly_payments.generated",
    entityType: "sponsor_monthly_payment",
    metadata: { year, month, created: data }
  });
  revalidatePath("/admin/payments");
  redirect(target(destination, "success", `تم إنشاء ${data ?? 0} سجل دفع شهري جديد`));
}

export async function updateSponsorPaymentAction(formData: FormData) {
  const parsed = sponsorMonthlyPaymentSchema.safeParse({
    id: formData.get("id"),
    expectedAmount: formData.get("expectedAmount"),
    receivedAmount: formData.get("receivedAmount"),
    paymentDate: formData.get("paymentDate"),
    internalNotes: formData.get("internalNotes")
  });
  const destination = returnPath(formData, "/admin/payments");
  if (!parsed.success) {
    redirect(target(destination, "error", parsed.error.issues[0]?.message ?? "بيانات الدفع غير صحيحة"));
  }

  const { profile, supabase } = await adminContext();
  const { data: previous } = await supabase
    .from("sponsor_monthly_payments")
    .select("expected_amount_snapshot,received_amount,payment_status,payment_date,internal_notes")
    .eq("id", parsed.data.id)
    .maybeSingle();
  if (!previous) redirect(target(destination, "error", "سجل الدفع غير موجود"));

  const { error } = await supabase
    .from("sponsor_monthly_payments")
    .update({
      expected_amount_snapshot: parsed.data.expectedAmount,
      received_amount: parsed.data.receivedAmount,
      payment_date: parsed.data.paymentDate,
      internal_notes: parsed.data.internalNotes,
      confirmed_by: profile.id
    })
    .eq("id", parsed.data.id);
  if (error) redirect(target(destination, "error", "تعذر حفظ تصحيح الدفعة"));

  await writeAuditLog({
    actorId: profile.id,
    action: previous.received_amount === 0 ? "sponsor_payment.confirmed" : "sponsor_payment.corrected",
    entityType: "sponsor_monthly_payment",
    entityId: parsed.data.id,
    metadata: {
      before: previous,
      expectedAmount: parsed.data.expectedAmount,
      receivedAmount: parsed.data.receivedAmount,
      paymentDate: parsed.data.paymentDate
    }
  });
  revalidatePath("/admin", "layout");
  revalidatePath("/donor", "layout");
  redirect(target(destination, "success", "تم حفظ دفعة المتبرع وتحديث حالتها"));
}

export async function undoSponsorPaymentAction(formData: FormData) {
  const id = String(formData.get("id") ?? "");
  const destination = returnPath(formData, "/admin/payments");
  if (!z.uuid().safeParse(id).success) redirect(target(destination, "error", "سجل الدفع غير صحيح"));
  const { profile, supabase } = await adminContext();
  const { data: previous, error } = await supabase
    .from("sponsor_monthly_payments")
    .update({ received_amount: 0, payment_date: null, confirmed_by: profile.id })
    .eq("id", id)
    .select("received_amount,payment_status,payment_date")
    .single();
  if (error) redirect(target(destination, "error", "تعذر إلغاء تأكيد الدفعة"));
  await writeAuditLog({
    actorId: profile.id,
    action: "sponsor_payment.confirmation_undone",
    entityType: "sponsor_monthly_payment",
    entityId: id,
    metadata: { previous }
  });
  revalidatePath("/admin", "layout");
  revalidatePath("/donor", "layout");
  redirect(target(destination, "success", "تم إلغاء تأكيد الدفعة"));
}

export async function deleteSponsorPaymentAction(formData: FormData) {
  const id = String(formData.get("id") ?? "");
  const destination = returnPath(formData, "/admin/payments");
  if (!z.uuid().safeParse(id).success) redirect(target(destination, "error", "سجل الدفع غير صحيح"));
  const { profile, supabase } = await adminContext();
  const { error } = await supabase.rpc("delete_sponsor_monthly_payment", {
    p_payment_id: id,
    p_actor: profile.id
  });
  if (error) redirect(target(destination, "error", "تعذر حذف سجل الدفع الشهري"));
  await writeAuditLog({
    actorId: profile.id,
    action: "sponsor_payment.deleted",
    entityType: "sponsor_monthly_payment",
    entityId: id
  });
  revalidatePath("/admin", "layout");
  redirect(target(destination, "success", "تم حذف سجل الدفع الشهري"));
}

function receiptPayload(stored: StoredPrivateFile) {
  return {
    stored_name: stored.storedName,
    original_name: stored.originalName,
    extension: stored.extension,
    mime_type: stored.mimeType,
    size_bytes: stored.sizeBytes,
    sha256: stored.sha256
  };
}

export async function createTransferAction(formData: FormData) {
  const parsed = orphanTransferSchema.safeParse({
    sponsorId: formData.get("sponsorId"),
    orphanId: formData.get("orphanId"),
    amount: formData.get("amount"),
    transferDate: formData.get("transferDate"),
    reference: formData.get("reference"),
    sponsorVisibleNotes: formData.get("sponsorVisibleNotes"),
    internalNotes: formData.get("internalNotes")
  });
  if (!parsed.success) {
    redirect(
      target(
        "/admin/transfers",
        "error",
        parsed.error.issues[0]?.message ?? "بيانات التحويل غير صحيحة"
      )
    );
  }

  const { profile, supabase } = await adminContext();
  const hasActiveLink = await activeSponsorOrphanLinkExists(
    supabase,
    parsed.data.sponsorId,
    parsed.data.orphanId
  ).catch(() => false);
  if (!hasActiveLink) {
    redirect(target("/admin/transfers", "error", "اليتيم المختار غير مرتبط بالمتبرع المحدد بعلاقة نشطة"));
  }
  const receipt = formData.get("receipt");
  let stored: StoredPrivateFile | null = null;
  let sponsorCount = 0;
  try {
    if (receipt instanceof File && receipt.size > 0) {
      const uploadIdentity = await orphanUploadIdentity(supabase, parsed.data.orphanId);
      stored = await savePrivateUpload(receipt, {
        orphan: uploadIdentity,
        kind: "receipts",
        imageOnly: true
      });
    }
    const { data, error } = await supabase.rpc("create_orphan_transfer_for_sponsor", {
      p_sponsor_id: parsed.data.sponsorId,
      p_orphan_id: parsed.data.orphanId,
      p_amount: parsed.data.amount,
      p_transfer_date: parsed.data.transferDate,
      p_reference: parsed.data.reference,
      p_sponsor_visible_notes: parsed.data.sponsorVisibleNotes,
      p_internal_notes: parsed.data.internalNotes,
      p_actor: profile.id,
      p_receipt: stored ? receiptPayload(stored) : null
    });
    if (error?.message.includes("no active sponsors")) {
      throw new Error("لا توجد كفالة نشطة مرتبطة بهذا اليتيم");
    }
    if (error) throw new Error("تعذر حفظ التحويل");
    const result = Array.isArray(data) ? data[0] : data;
    sponsorCount = Number(result?.sponsor_count ?? 0);
    await writeAuditLog({
      actorId: profile.id,
      action: "orphan_transfer.created",
      entityType: "orphan_transfer",
      entityId: result?.transfer_id,
      metadata: {
        selectedSponsorId: parsed.data.sponsorId,
        orphanId: parsed.data.orphanId,
        sponsorCount,
        amount: parsed.data.amount,
        receiptUploaded: Boolean(stored)
      }
    });
  } catch (error) {
    if (stored) await removePrivateUpload(stored.absolutePath);
    redirect(target("/admin/transfers", "error", error instanceof Error ? error.message : "تعذر حفظ التحويل"));
  }

  revalidatePath("/admin", "layout");
  revalidatePath("/donor", "layout");
  redirect(target("/admin/transfers", "success", `تم حفظ التحويل وإظهاره لـ ${sponsorCount} متبرع`));
}

export async function updateTransferAction(formData: FormData) {
  const parsed = orphanTransferSchema.safeParse({
    id: formData.get("id"),
    sponsorId: formData.get("sponsorId"),
    orphanId: formData.get("orphanId"),
    amount: formData.get("amount"),
    transferDate: formData.get("transferDate"),
    reference: formData.get("reference"),
    sponsorVisibleNotes: formData.get("sponsorVisibleNotes"),
    internalNotes: formData.get("internalNotes")
  });
  const destination = returnPath(formData, "/admin/transfers");
  if (!parsed.success || !parsed.data.id) {
    redirect(target(destination, "error", parsed.success ? "سجل التحويل غير صحيح" : parsed.error.issues[0]?.message ?? "بيانات التحويل غير صحيحة"));
  }

  const { profile, supabase } = await adminContext();
  const { data: previous, error: previousError } = await supabase
    .from("orphan_transfers")
    .select("*")
    .eq("id", parsed.data.id)
    .maybeSingle();
  if (previousError || !previous) redirect(target(destination, "error", "سجل التحويل غير موجود"));

  const hasActiveLink = await activeSponsorOrphanLinkExists(
    supabase,
    parsed.data.sponsorId,
    parsed.data.orphanId
  ).catch(() => false);
  if (!hasActiveLink) {
    redirect(target(destination, "error", "اليتيم المختار غير مرتبط بالمتبرع المحدد بعلاقة نشطة"));
  }

  const orphanChanged = previous.orphan_id !== parsed.data.orphanId;
  let previousUploadIdentity: OrphanUploadIdentity | null = null;
  let nextUploadIdentity: OrphanUploadIdentity | null = null;
  let movedReceipt:
    | {
        storedName: string;
        extension: string;
      }
    | null = null;

  if (orphanChanged) {
    const [{ data: receipt, error: receiptError }, previousIdentity, nextIdentity] = await Promise.all([
      supabase
        .from("transfer_receipts")
        .select("file_assets(stored_name,extension)")
        .eq("orphan_transfer_id", parsed.data.id)
        .maybeSingle(),
      orphanUploadIdentity(supabase, previous.orphan_id),
      orphanUploadIdentity(supabase, parsed.data.orphanId)
    ]);
    if (receiptError) redirect(target(destination, "error", "تعذر التحقق من إيصال التحويل"));
    previousUploadIdentity = previousIdentity;
    nextUploadIdentity = nextIdentity;
    const receiptAsset = Array.isArray(receipt?.file_assets)
      ? receipt.file_assets[0] ?? null
      : receipt?.file_assets ?? null;

    if (receiptAsset) {
      const moved = await movePrivateUploadByReference(
        previousUploadIdentity,
        nextUploadIdentity,
        receiptAsset.stored_name,
        receiptAsset.extension,
        "receipts"
      ).catch(() => false);
      if (!moved) {
        redirect(target(destination, "error", "تعذر نقل الإيصال إلى مجلد اليتيم المختار"));
      }
      movedReceipt = {
        storedName: receiptAsset.stored_name,
        extension: receiptAsset.extension
      };
    }
  }

  const { data: updateResult, error } = await supabase.rpc("update_orphan_transfer", {
    p_transfer_id: parsed.data.id,
    p_sponsor_id: parsed.data.sponsorId,
    p_orphan_id: parsed.data.orphanId,
    p_amount: parsed.data.amount,
    p_transfer_date: parsed.data.transferDate,
    p_reference: parsed.data.reference,
    p_sponsor_visible_notes: parsed.data.sponsorVisibleNotes,
    p_internal_notes: parsed.data.internalNotes,
    p_actor: profile.id
  });
  if (error) {
    let receiptRestored = true;
    if (movedReceipt && previousUploadIdentity && nextUploadIdentity) {
      receiptRestored = await movePrivateUploadByReference(
        nextUploadIdentity,
        previousUploadIdentity,
        movedReceipt.storedName,
        movedReceipt.extension,
        "receipts"
      ).catch(() => false);
    }
    redirect(
      target(
        destination,
        "error",
        receiptRestored
          ? "تعذر تحديث التحويل أو أن العلاقة المختارة غير صالحة"
          : "تعذر تحديث التحويل واستعادة مسار الإيصال"
      )
    );
  }
  const result = Array.isArray(updateResult) ? updateResult[0] : updateResult;

  await writeAuditLog({
    actorId: profile.id,
    action: "orphan_transfer.updated",
    entityType: "orphan_transfer",
    entityId: parsed.data.id,
    metadata: {
      before: previous,
      selectedSponsorId: parsed.data.sponsorId,
      orphanId: parsed.data.orphanId,
      orphanChanged,
      sponsorCount: Number(result?.sponsor_count ?? 0),
      amount: parsed.data.amount
    }
  });
  revalidatePath("/admin", "layout");
  revalidatePath("/donor", "layout");
  redirect(target(destination, "success", "تم تحديث التحويل"));
}

export async function deleteTransferAction(formData: FormData) {
  const id = String(formData.get("id") ?? "");
  const destination = returnPath(formData, "/admin/transfers");
  if (!z.uuid().safeParse(id).success) redirect(target(destination, "error", "سجل التحويل غير صحيح"));
  const { profile, supabase } = await adminContext();
  const { data: transfer } = await supabase
    .from("orphan_transfers")
    .select("orphan_id")
    .eq("id", id)
    .maybeSingle();
  if (!transfer) redirect(target(destination, "error", "سجل التحويل غير موجود"));
  const uploadIdentity = await orphanUploadIdentity(supabase, transfer.orphan_id).catch(() =>
    redirect(target(destination, "error", "تعذر العثور على مجلد ملفات اليتيم"))
  );
  const { data, error } = await supabase.rpc("delete_orphan_transfer", {
    p_transfer_id: id,
    p_actor: profile.id
  });
  if (error) redirect(target(destination, "error", "تعذر حذف التحويل"));
  const result = Array.isArray(data) ? data[0] : data;
  if (result?.old_stored_name && result?.old_extension) {
    await removePrivateUploadByReference(
      uploadIdentity,
      result.old_stored_name,
      result.old_extension,
      "receipts"
    );
  }
  await writeAuditLog({
    actorId: profile.id,
    action: "orphan_transfer.deleted",
    entityType: "orphan_transfer",
    entityId: id
  });
  revalidatePath("/admin", "layout");
  revalidatePath("/donor", "layout");
  redirect(target(destination, "success", "تم حذف التحويل وإيصاله"));
}

export async function replaceTransferReceiptAction(formData: FormData) {
  const transferId = String(formData.get("transferId") ?? "");
  const file = formData.get("receipt");
  const destination = returnPath(formData, "/admin/transfers");
  if (!z.uuid().safeParse(transferId).success || !(file instanceof File) || file.size <= 0) {
    redirect(target(destination, "error", "اختر صورة إيصال صحيحة"));
  }
  const { profile, supabase } = await adminContext();
  const { data: transfer } = await supabase
    .from("orphan_transfers")
    .select("orphan_id")
    .eq("id", transferId)
    .maybeSingle();
  if (!transfer) redirect(target(destination, "error", "سجل التحويل غير موجود"));
  const uploadIdentity = await orphanUploadIdentity(supabase, transfer.orphan_id).catch(() =>
    redirect(target(destination, "error", "تعذر العثور على مجلد ملفات اليتيم"))
  );
  let stored: StoredPrivateFile | null = null;
  try {
    stored = await savePrivateUpload(file, {
      orphan: uploadIdentity,
      kind: "receipts",
      imageOnly: true
    });
    const { data, error } = await supabase.rpc("replace_transfer_receipt", {
      p_transfer_id: transferId,
      p_stored_name: stored.storedName,
      p_original_name: stored.originalName,
      p_extension: stored.extension,
      p_mime_type: stored.mimeType,
      p_size_bytes: stored.sizeBytes,
      p_sha256: stored.sha256,
      p_actor: profile.id
    });
    if (error) throw error;
    const result = Array.isArray(data) ? data[0] : data;
    if (result?.old_stored_name && result?.old_extension) {
      await removePrivateUploadByReference(
        uploadIdentity,
        result.old_stored_name,
        result.old_extension,
        "receipts"
      );
    }
    await writeAuditLog({
      actorId: profile.id,
      action: result?.old_stored_name ? "transfer_receipt.replaced" : "transfer_receipt.uploaded",
      entityType: "orphan_transfer",
      entityId: transferId,
      metadata: { fileId: result?.new_file_id }
    });
  } catch (error) {
    if (stored) await removePrivateUpload(stored.absolutePath);
    redirect(target(destination, "error", error instanceof Error ? error.message : "تعذر حفظ الإيصال"));
  }
  revalidatePath("/admin/transfers");
  revalidatePath("/donor", "layout");
  redirect(target(destination, "success", "تم حفظ الإيصال وتأكيد التحويل"));
}

export async function deleteTransferReceiptAction(formData: FormData) {
  const transferId = String(formData.get("transferId") ?? "");
  const destination = returnPath(formData, "/admin/transfers");
  if (!z.uuid().safeParse(transferId).success) redirect(target(destination, "error", "سجل التحويل غير صحيح"));
  const { profile, supabase } = await adminContext();
  const { data: transfer } = await supabase
    .from("orphan_transfers")
    .select("orphan_id")
    .eq("id", transferId)
    .maybeSingle();
  if (!transfer) redirect(target(destination, "error", "سجل التحويل غير موجود"));
  const uploadIdentity = await orphanUploadIdentity(supabase, transfer.orphan_id).catch(() =>
    redirect(target(destination, "error", "تعذر العثور على مجلد ملفات اليتيم"))
  );
  const { data, error } = await supabase.rpc("delete_transfer_receipt", {
    p_transfer_id: transferId,
    p_actor: profile.id
  });
  if (error) redirect(target(destination, "error", "تعذر حذف الإيصال"));
  const result = Array.isArray(data) ? data[0] : data;
  if (result?.old_stored_name && result?.old_extension) {
    await removePrivateUploadByReference(
      uploadIdentity,
      result.old_stored_name,
      result.old_extension,
      "receipts"
    );
  }
  await writeAuditLog({
    actorId: profile.id,
    action: "transfer_receipt.deleted",
    entityType: "orphan_transfer",
    entityId: transferId
  });
  revalidatePath("/admin/transfers");
  revalidatePath("/donor", "layout");
  redirect(target(destination, "success", "تم حذف الإيصال وأعيد التحويل إلى قيد الانتظار"));
}

export async function replaceOrphanDocumentAction(formData: FormData) {
  const orphanId = String(formData.get("orphanId") ?? "");
  const type = orphanDocumentTypeSchema.safeParse(formData.get("documentType"));
  const file = formData.get("file");
  if (!z.uuid().safeParse(orphanId).success || !type.success || !(file instanceof File) || file.size <= 0) {
    redirect(target(`/admin/orphans/${orphanId}`, "error", "بيانات الوثيقة غير صحيحة"));
  }

  const { profile, supabase } = await adminContext();
  const uploadIdentity = await orphanUploadIdentity(supabase, orphanId).catch(() =>
    redirect(target(`/admin/orphans/${orphanId}`, "error", "تعذر العثور على مجلد ملفات اليتيم"))
  );
  let stored: StoredPrivateFile | null = null;
  try {
    stored = await savePrivateUpload(file, {
      orphan: uploadIdentity,
      kind: "documents",
      imageOnly: true
    });
    const { data, error } = await supabase.rpc("replace_orphan_document", {
      p_orphan_id: orphanId,
      p_document_type: type.data,
      p_title: orphanDocumentLabels[type.data],
      p_stored_name: stored.storedName,
      p_original_name: stored.originalName,
      p_extension: stored.extension,
      p_mime_type: stored.mimeType,
      p_size_bytes: stored.sizeBytes,
      p_sha256: stored.sha256,
      p_actor: profile.id
    });
    if (error) throw error;

    const replaced = Array.isArray(data) ? data[0] : data;
    if (replaced?.old_stored_name && replaced?.old_extension) {
      await removePrivateUploadByReference(
        uploadIdentity,
        replaced.old_stored_name,
        replaced.old_extension,
        "documents"
      );
    }
    await writeAuditLog({
      actorId: profile.id,
      action: replaced?.old_stored_name ? "orphan_document.replaced" : "orphan_document.uploaded",
      entityType: "orphan",
      entityId: orphanId,
      metadata: { documentType: type.data, fileId: replaced?.new_file_id }
    });
  } catch (error) {
    if (stored) await removePrivateUpload(stored.absolutePath);
    redirect(target(`/admin/orphans/${orphanId}`, "error", error instanceof Error ? error.message : "تعذر حفظ الوثيقة"));
  }

  revalidatePath(`/admin/orphans/${orphanId}`);
  revalidatePath("/donor", "layout");
  redirect(target(`/admin/orphans/${orphanId}`, "success", "تم حفظ الوثيقة بأمان"));
}

export async function deleteOrphanDocumentAction(formData: FormData) {
  const orphanId = String(formData.get("orphanId") ?? "");
  const type = orphanDocumentTypeSchema.safeParse(formData.get("documentType"));
  if (!z.uuid().safeParse(orphanId).success || !type.success) {
    redirect(target(`/admin/orphans/${orphanId}`, "error", "بيانات الوثيقة غير صحيحة"));
  }
  const { profile, supabase } = await adminContext();
  const uploadIdentity = await orphanUploadIdentity(supabase, orphanId).catch(() =>
    redirect(target(`/admin/orphans/${orphanId}`, "error", "تعذر العثور على مجلد ملفات اليتيم"))
  );
  const { data, error } = await supabase.rpc("delete_orphan_document", {
    p_orphan_id: orphanId,
    p_document_type: type.data,
    p_actor: profile.id
  });
  if (error) redirect(target(`/admin/orphans/${orphanId}`, "error", "تعذر حذف الوثيقة"));
  const result = Array.isArray(data) ? data[0] : data;
  if (result?.old_stored_name && result?.old_extension) {
    await removePrivateUploadByReference(
      uploadIdentity,
      result.old_stored_name,
      result.old_extension,
      "documents"
    );
  }
  await writeAuditLog({
    actorId: profile.id,
    action: "orphan_document.deleted",
    entityType: "orphan",
    entityId: orphanId,
    metadata: { documentType: type.data }
  });
  revalidatePath(`/admin/orphans/${orphanId}`);
  revalidatePath("/donor", "layout");
  redirect(target(`/admin/orphans/${orphanId}`, "success", "تم حذف الوثيقة"));
}

export async function createNotificationAction(formData: FormData) {
  const recipientId = String(formData.get("recipientId") ?? "");
  const title = String(formData.get("title") ?? "").trim();
  const body = String(formData.get("body") ?? "").trim();
  if (!z.uuid().safeParse(recipientId).success || title.length < 3 || body.length < 3) {
    redirect(target("/admin/notifications", "error", "بيانات الإشعار غير صحيحة"));
  }
  const { profile, supabase } = await adminContext();
  const { error } = await supabase
    .from("notifications")
    .insert({ recipient_id: recipientId, title, body, link: nonEmpty(formData.get("link")) });
  if (error) redirect(target("/admin/notifications", "error", "تعذر إرسال الإشعار"));
  await writeAuditLog({
    actorId: profile.id,
    action: "notification.created",
    entityType: "profile",
    entityId: recipientId
  });
  revalidatePath("/admin/notifications");
  redirect(target("/admin/notifications", "success", "تم إرسال الإشعار"));
}

export async function updateSettingsAction(formData: FormData) {
  const defaultAmount = asNumber(formData.get("defaultAmount"), -1);
  const organizationName = String(formData.get("organizationName") ?? "").trim();
  const idleMinutes = asNumber(formData.get("idleMinutes"), -1);
  if (defaultAmount < 1000 || organizationName.length < 2 || idleMinutes < 5 || idleMinutes > 1440) {
    redirect(target("/admin/settings", "error", "إعدادات غير صحيحة"));
  }
  const { profile, supabase } = await adminContext();
  const rows = [
    { key: "default_monthly_support", value: defaultAmount, updated_by: profile.id },
    { key: "organization_name", value: organizationName, updated_by: profile.id },
    { key: "session_idle_minutes", value: idleMinutes, updated_by: profile.id }
  ];
  const { error } = await supabase.from("app_settings").upsert(rows);
  if (error) redirect(target("/admin/settings", "error", "تعذر تحديث الإعدادات"));
  await writeAuditLog({ actorId: profile.id, action: "settings.updated", entityType: "app_settings" });
  revalidatePath("/admin/settings");
  redirect(target("/admin/settings", "success", "تم حفظ الإعدادات"));
}
