"use server";

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

const ExperienceSchema = z.object({
  company: z.string().min(1, "Company is required"),
  role: z.string().min(1, "Role is required"),
  startDate: z.coerce.date(),
  endDate: z.coerce.date().nullable().optional(),
  current: z.boolean().default(false),
  description: z.string().min(1, "Description is required"),
  highlights: z.array(z.string()).optional().default([]),
  techStack: z.array(z.string()).optional().default([]),
  order: z.coerce.number().default(0),
});

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

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

  revalidatePath("/dashboard/experience");
  revalidatePath("/experience");
  return experience;
}

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

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

  revalidatePath("/dashboard/experience");
  revalidatePath("/experience");
  return experience;
}

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

  revalidatePath("/dashboard/experience");
  revalidatePath("/experience");
  return experience;
}

export async function getExperiences() {
  return await prisma.experience.findMany({
    orderBy: { startDate: "desc" },
  });
}
