"use server";

import { prisma } from "@/core/db/prisma";
import { verifySession } from "@/core/security/session";
import { revalidatePath } from "next/cache";
import { z } from "zod";

const contactSchema = z.object({
  senderName: z.string().min(1, "Nama harus diisi"),
  senderEmail: z.string().email("Email tidak valid"),
  content: z.string().min(5, "Pesan minimal 5 karakter"),
});

// Public action — no auth required
export async function sendMessageAction(prevState: any, formData: FormData) {
  const data = {
    senderName: formData.get("name") as string,
    senderEmail: formData.get("email") as string,
    content: formData.get("message") as string,
  };

  const validation = contactSchema.safeParse(data);
  if (!validation.success) {
    return { success: false, message: validation.error.issues[0].message };
  }

  try {
    await prisma.message.create({
      data: {
        senderName: validation.data.senderName,
        senderEmail: validation.data.senderEmail,
        content: validation.data.content,
      },
    });
    revalidatePath("/admin/dashboard/inbox");
    return { success: true };
  } catch (error) {
    console.error(error);
    return { success: false, message: "Gagal mengirim pesan. Coba lagi." };
  }
}

export async function markMessageAsReadAction(id: string) {
  const session = await verifySession();
  if (!session) return { success: false, message: "Unauthorized" };

  try {
    await prisma.message.update({
      where: { id },
      data: { isRead: true },
    });
    revalidatePath("/admin/dashboard/inbox");
    return { success: true };
  } catch (error) {
    return { success: false, message: "Failed to mark as read" };
  }
}

export async function deleteMessageAction(id: string) {
  const session = await verifySession();
  if (!session) return { success: false, message: "Unauthorized" };

  try {
    await prisma.message.delete({ where: { id } });
    revalidatePath("/admin/dashboard/inbox");
    return { success: true };
  } catch (error) {
    return { success: false, message: "Failed to delete message" };
  }
}
