import { prisma } from "@/lib/db";
import type { Project } from "@prisma/client";

export type ProjectWithArrays = Omit<Project, "gallery" | "techStack" | "toolsUsed"> & {
  gallery: string[];
  techStack: string[];
  toolsUsed: string[];
};

function parseArrayField(val: string | null): string[] {
  if (!val) return [];
  try { return JSON.parse(val); } catch { return []; }
}

export function parseProject(p: Project): ProjectWithArrays {
  return {
    ...p,
    gallery: parseArrayField(p.gallery),
    techStack: parseArrayField(p.techStack),
    toolsUsed: parseArrayField(p.toolsUsed),
  };
}

export async function getAllProjects(locale: string): Promise<ProjectWithArrays[]> {
  const rows = await prisma.project.findMany({
    where: { locale },
    orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }],
  });
  return rows.map(parseProject);
}

export async function getProjectsByType(locale: string, projectType: string): Promise<ProjectWithArrays[]> {
  const rows = await prisma.project.findMany({
    where: { locale, projectType },
    orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }],
  });
  return rows.map(parseProject);
}

export async function getProjectBySlug(slug: string): Promise<ProjectWithArrays | null> {
  const row = await prisma.project.findUnique({ where: { slug } });
  return row ? parseProject(row) : null;
}

export async function getAllProjectSlugs(): Promise<{ slug: string; locale: string }[]> {
  return prisma.project.findMany({ select: { slug: true, locale: true } });
}
