'use server'

import { prisma } from "@/lib/prisma";
import { revalidatePath } from "next/cache";
import { z } from "zod";

const MenuSchema = z.object({
    nameId: z.string().min(1, "Nama (ID) wajib diisi"),
    nameEn: z.string().optional(),
    descriptionId: z.string().min(1, "Deskripsi (ID) wajib diisi"),
    descriptionEn: z.string().optional(),
    slug: z.string().min(1, "Slug wajib diisi"),
    parentId: z.string().optional().nullable(),
    isActive: z.boolean().default(true),
});

export async function createMenu(prevState: any, formData: FormData) {
    const validatedFields = MenuSchema.safeParse({
        nameId: formData.get("nameId"),
        nameEn: formData.get("nameEn"),
        descriptionId: formData.get("descriptionId"),
        descriptionEn: formData.get("descriptionEn"),
        slug: formData.get("slug"),
        parentId: formData.get("parentId") === "null" ? null : formData.get("parentId"),
        isActive: formData.get("isActive") === "on",
    });

    if (!validatedFields.success) {
        return {
            error: validatedFields.error.flatten().fieldErrors,
        };
    }

    const { nameId, nameEn, descriptionId, descriptionEn, slug, parentId, isActive } = validatedFields.data;

    try {
        await prisma.menu.create({
            data: {
                name: {
                    id: nameId,
                    en: nameEn || nameId,
                },
                description: {
                    id: descriptionId,
                    en: descriptionEn || descriptionId,
                },
                slug,
                parentId,
                isActive,
                updatedBy: "system", // TODO: Get actual user
            },
        });

        revalidatePath("/dashboard/menu");
        return { success: true, message: "Menu berhasil dibuat" };
    } catch (error) {
        console.error("Failed to create menu:", error);
        return { error: "Gagal membuat menu. Pastikan slug unik." };
    }
}

export async function updateMenu(id: string, prevState: any, formData: FormData) {
    const validatedFields = MenuSchema.safeParse({
        nameId: formData.get("nameId"),
        nameEn: formData.get("nameEn"),
        descriptionId: formData.get("descriptionId"),
        descriptionEn: formData.get("descriptionEn"),
        slug: formData.get("slug"),
        parentId: formData.get("parentId") === "null" ? null : formData.get("parentId"),
        isActive: formData.get("isActive") === "on",
    });

    if (!validatedFields.success) {
        return {
            error: validatedFields.error.flatten().fieldErrors,
        };
    }

    const { nameId, nameEn, descriptionId, descriptionEn, slug, parentId, isActive } = validatedFields.data;

    try {
        await prisma.menu.update({
            where: { id },
            data: {
                name: {
                    id: nameId,
                    en: nameEn || nameId,
                },
                description: {
                    id: descriptionId,
                    en: descriptionEn || descriptionId,
                },
                slug,
                parentId,
                isActive,
                updatedBy: "system", // TODO: Get actual user
            },
        });

        revalidatePath("/dashboard/menu");
        return { success: true, message: "Menu berhasil diperbarui" };
    } catch (error) {
        console.error("Failed to update menu:", error);
        return { error: "Gagal memperbarui menu." };
    }
}

export async function deleteMenu(id: string) {
    try {
        await prisma.menu.delete({
            where: { id },
        });
        revalidatePath("/dashboard/menu");
        return { success: true, message: "Menu berhasil dihapus" };
    } catch (error) {
        console.error("Failed to delete menu:", error);
        return { error: "Gagal menghapus menu" };
    }
}
