"use server";

import { prisma } from "@/core/db/prisma";
import { verifySession } from "@/core/security/session";
import { revalidatePath } from "next/cache";
import { z } from "zod";

const experienceSchema = z.object({
  year: z.string().min(1, "Year/period is required"),
  title: z.string().min(1, "Job title is required"),
  company: z.string().min(1, "Company name is required"),
  description: z.string().min(1, "Description is required"),
  achievements: z.string().optional(),
  order: z.coerce.number().default(0),
});

function parseAchievements(raw: string | undefined): string[] {
  if (!raw) return [];
  return raw
    .split("\n")
    .map((s) => s.trim())
    .filter(Boolean);
}

export async function createExperienceAction(prevState: any, formData: FormData) {
  const session = await verifySession();
  if (!session) return { success: false, message: "Unauthorized" };

  const data = {
    year: formData.get("year") as string,
    title: formData.get("title") as string,
    company: formData.get("company") as string,
    description: formData.get("description") as string,
    achievements: formData.get("achievements") as string,
    order: formData.get("order") as string,
  };

  const validation = experienceSchema.safeParse(data);
  if (!validation.success) {
    return { success: false, message: validation.error.issues[0].message };
  }

  try {
    await prisma.experience.create({
      data: {
        year: validation.data.year,
        title: validation.data.title,
        company: validation.data.company,
        description: validation.data.description,
        achievements: parseAchievements(validation.data.achievements),
        order: validation.data.order,
      },
    });
    revalidatePath("/admin/dashboard/experience");
    revalidatePath("/");
    return { success: true };
  } catch (error) {
    console.error(error);
    return { success: false, message: "Failed to create experience" };
  }
}

export async function updateExperienceAction(
  id: string,
  prevState: any,
  formData: FormData
) {
  const session = await verifySession();
  if (!session) return { success: false, message: "Unauthorized" };

  const data = {
    year: formData.get("year") as string,
    title: formData.get("title") as string,
    company: formData.get("company") as string,
    description: formData.get("description") as string,
    achievements: formData.get("achievements") as string,
    order: formData.get("order") as string,
  };

  const validation = experienceSchema.safeParse(data);
  if (!validation.success) {
    return { success: false, message: validation.error.issues[0].message };
  }

  try {
    await prisma.experience.update({
      where: { id },
      data: {
        year: validation.data.year,
        title: validation.data.title,
        company: validation.data.company,
        description: validation.data.description,
        achievements: parseAchievements(validation.data.achievements),
        order: validation.data.order,
      },
    });
    revalidatePath("/admin/dashboard/experience");
    revalidatePath("/");
    return { success: true };
  } catch (error) {
    return { success: false, message: "Failed to update experience" };
  }
}

export async function deleteExperienceAction(id: string) {
  const session = await verifySession();
  if (!session) return { success: false, message: "Unauthorized" };

  try {
    await prisma.experience.delete({ where: { id } });
    revalidatePath("/admin/dashboard/experience");
    revalidatePath("/");
    return { success: true };
  } catch (error) {
    return { success: false, message: "Failed to delete experience" };
  }
}
