"use server";

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

const ProjectSchema = z.object({
  title: z.string().min(1, "Title is required"),
  description: z.string().min(1, "Description is required"),
  imageUrl: z.string().optional().nullable(),
  liveUrl: z.string().optional().nullable(),
  githubUrl: z.string().optional().nullable(),
  techStack: z.array(z.string()).min(1, "At least one tech stack is required"),
  featured: z.boolean().default(false),
  order: z.coerce.number().default(0),
});

export async function createProject(data: z.infer<typeof ProjectSchema>) {
  const validated = ProjectSchema.parse(data);

  const project = await prisma.project.create({
    data: validated,
  });

  revalidatePath("/dashboard/projects");
  revalidatePath("/projects");
  return project;
}

export async function updateProject(id: string, data: z.infer<typeof ProjectSchema>) {
  const validated = ProjectSchema.parse(data);

  const project = await prisma.project.update({
    where: { id },
    data: validated,
  });

  revalidatePath("/dashboard/projects");
  revalidatePath("/projects");
  return project;
}

export async function deleteProject(id: string) {
  const project = await prisma.project.delete({
    where: { id },
  });

  revalidatePath("/dashboard/projects");
  revalidatePath("/projects");
  return project;
}

export async function getProjects() {
  return await prisma.project.findMany({
    orderBy: [{ order: "asc" }, { createdAt: "desc" }],
  });
}
