'use server';

import { prisma } from './prisma';
import { revalidatePath } from 'next/cache';

// -------------------------------------------------------------------------------- //
// TABEL MATA KULIAH KURIKULUM UPI                                                    //
// -------------------------------------------------------------------------------- //

export async function createMatkul(formData: FormData) {
    const kode = formData.get('kode') as string;
    const nama = formData.get('nama') as string;
    const sks = Number(formData.get('sks'));
    const semester_rekomendasi = Number(formData.get('semester_rekomendasi'));
    const prodi = formData.get('prodi') as string;
    const kategori = formData.get('kategori') as string;

    try {
        await prisma.mataKuliah.create({
            data: {
                kode,
                nama,
                sks,
                semester_rekomendasi,
                prodi,
                kategori: kategori || null,
            }
        });

        revalidatePath('/admin/kurikulum');
        revalidatePath('/kinetik'); // Revalidate halaman user
        return { success: true };
    } catch (e: any) {
        return { error: e.message };
    }
}

export async function updateMatkul(id: string, formData: FormData) {
    const kode = formData.get('kode') as string;
    const nama = formData.get('nama') as string;
    const sks = Number(formData.get('sks'));
    const semester_rekomendasi = Number(formData.get('semester_rekomendasi'));
    const prodi = formData.get('prodi') as string;
    const kategori = formData.get('kategori') as string;

    try {
        await prisma.mataKuliah.update({
            where: { id },
            data: {
                kode,
                nama,
                sks,
                semester_rekomendasi,
                prodi,
                kategori: kategori || null,
            }
        });

        revalidatePath('/admin/kurikulum');
        revalidatePath('/kinetik');
        return { success: true };
    } catch (e: any) {
        return { error: e.message };
    }
}

export async function deleteMatkul(id: string) {
    try {
        await prisma.mataKuliah.delete({ where: { id } });
        revalidatePath('/admin/kurikulum');
        revalidatePath('/kinetik');
        return { success: true };
    } catch (e: any) {
        return { error: e.message };
    }
}

export async function importBulkMatkul(data: any[]) {
    try {
        if (!data || data.length === 0) return { error: 'Data kosong' };
        await prisma.mataKuliah.createMany({ data });
        revalidatePath('/admin/kurikulum');
        revalidatePath('/kinetik');
        return { success: true, count: data.length };
    } catch (e: any) {
        return { error: e.message };
    }
}
