"use server";

import { revalidatePath } from "next/cache";
import { db } from "@/lib/db";

export async function saveScholarshipAction(formData: FormData) {
  const id = formData.get("id") as string | null;
  const deadlineRaw = formData.get("deadline") as string | null;

  const data = {
    title: (formData.get("title") as string).trim(),
    provider: (formData.get("provider") as string | null)?.trim() || null,
    country: (formData.get("country") as string | null)?.trim() || null,
    amount: (formData.get("amount") as string | null)?.trim() || null,
    deadline: deadlineRaw ? new Date(deadlineRaw) : null,
    description: (formData.get("description") as string | null)?.trim() || null,
    applyLink: (formData.get("applyLink") as string | null)?.trim() || null,
    isActive: formData.get("isActive") === "true",
  };

  if (!data.title) return { error: "Title is required." };

  if (id) {
    await db.scholarship.update({ where: { id }, data });
  } else {
    await db.scholarship.create({ data });
  }

  revalidatePath("/scholarships");
  revalidatePath("/");
  revalidatePath("/admin/scholarships");
  return { ok: true };
}

export async function deleteScholarshipAction(id: string) {
  await db.scholarship.delete({ where: { id } });
  revalidatePath("/scholarships");
  revalidatePath("/");
  revalidatePath("/admin/scholarships");
  return { ok: true };
}

export async function toggleScholarshipActiveAction(id: string, isActive: boolean) {
  await db.scholarship.update({ where: { id }, data: { isActive } });
  revalidatePath("/scholarships");
  revalidatePath("/");
  revalidatePath("/admin/scholarships");
  return { ok: true };
}
