"use server";
import { db } from '@/lib/db';
import { noticia } from '@/db/schema';
import { eq } from 'drizzle-orm';
import { revalidatePath } from "next/cache";
import crypto from "crypto";

export async function createNoticia(formData: FormData) {
  const titulo    = formData.get("titulo") as string;
  const contenido = formData.get("contenido") as string;
  const resumen   = (formData.get("resumen") as string) || null;
  const colegioId = (formData.get("colegioId") as string) || null;
  const publicado = formData.get("publicado") === "on";

  try {
    await db.insert(noticia).values({
      id: crypto.randomUUID(),
      titulo,
      contenido,
      resumen,
      colegioId: colegioId || null,
      publicado,
      updatedAt: new Date()
    });
    revalidatePath("/dashboard/noticias");
    revalidatePath("/noticias");
    return { success: true };
  } catch (error) {
    console.error(error);
    return { success: false, error: "Error al crear la noticia." };
  }
}

export async function updateNoticia(id: string, formData: FormData) {
  const titulo    = formData.get("titulo") as string;
  const contenido = formData.get("contenido") as string;
  const resumen   = (formData.get("resumen") as string) || null;
  const colegioId = (formData.get("colegioId") as string) || null;
  const publicado = formData.get("publicado") === "on";

  try {
    await db.update(noticia)
      .set({
        titulo,
        contenido,
        resumen,
        colegioId: colegioId || null,
        publicado,
        updatedAt: new Date()
      })
      .where(eq(noticia.id, id));
    revalidatePath("/dashboard/noticias");
    revalidatePath("/noticias");
    return { success: true };
  } catch (error) {
    return { success: false, error: "Error al actualizar." };
  }
}

export async function deleteNoticia(id: string) {
  try {
    await db.update(noticia)
      .set({ activo: false, updatedAt: new Date() })
      .where(eq(noticia.id, id));
    revalidatePath("/dashboard/noticias");
    revalidatePath("/noticias");
    return { success: true };
  } catch (error) {
    return { success: false, error: "Error al eliminar." };
  }
}

export async function togglePublicado(id: string, publicado: boolean) {
  try {
    await db.update(noticia)
      .set({ publicado, updatedAt: new Date() })
      .where(eq(noticia.id, id));
    revalidatePath("/dashboard/noticias");
    revalidatePath("/noticias");
    return { success: true };
  } catch (error) {
    return { success: false, error: "Error al cambiar estado." };
  }
}
