"use server";

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

const BlogSchema = z.object({
  title: z.string().min(1, "Title is required"),
  slug: z.string().min(1, "Slug is required"),
  content: z.string().min(1, "Content is required"),
  excerpt: z.string().optional(),
  status: z.nativeEnum(BlogStatus),
  publishedAt: z.coerce.date().nullable().optional(),
  tags: z.array(z.string()).optional(),
});

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

  const blog = await prisma.blog.create({
    data: {
      title: validated.title,
      slug: validated.slug,
      content: validated.content,
      excerpt: validated.excerpt,
      status: validated.status,
      publishedAt: validated.status === BlogStatus.PUBLISHED ? new Date() : null,
      tags: {
        connectOrCreate: validated.tags?.map((tag) => ({
          where: { name: tag },
          create: { name: tag },
        })),
      },
    },
  });

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

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

  const blog = await prisma.blog.update({
    where: { id },
    data: {
      title: validated.title,
      slug: validated.slug,
      content: validated.content,
      excerpt: validated.excerpt,
      status: validated.status,
      publishedAt: validated.status === BlogStatus.PUBLISHED ? new Date() : null,
      tags: {
        set: [], // Clear existing tags
        connectOrCreate: validated.tags?.map((tag) => ({
          where: { name: tag },
          create: { name: tag },
        })),
      },
    },
  });

  revalidatePath("/dashboard/blog");
  revalidatePath("/blog");
  revalidatePath(`/blog/${blog.slug}`);
  return blog;
}

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

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

export async function getBlogs() {
  return await prisma.blog.findMany({
    orderBy: { createdAt: "desc" },
    include: { tags: true },
  });
}
