import { prisma } from "@/lib/db";
import { slugify } from "./slug-vi";

export interface PageInput {
  id?: string;
  slug: string | null;
  title: string;
  content: string;
  status: "draft" | "published";
  publishedAt?: Date | null;
  metaTitle?: string | null;
  metaDesc?: string | null;
  metaKeywords?: string | null;
  ogImage?: string | null;
  canonicalUrl?: string | null;
  noIndex?: boolean;
  showInFooter?: boolean;
  footerOrder?: number;
  authorId?: string | null;
}

export function makeSlug(input: string): string {
  return (slugify(input) || "untitled").slice(0, 80);
}

async function uniqueSlug(base: string, excludeId?: string): Promise<string> {
  let candidate = base;
  let i = 2;
  while (true) {
    const exists = await prisma.page.findUnique({ where: { slug: candidate }, select: { id: true } });
    if (!exists || exists.id === excludeId) return candidate;
    candidate = `${base}-${i++}`;
    if (i > 50) return `${base}-${Date.now()}`;
  }
}

export async function createPage(input: PageInput) {
  const baseSlug = input.slug ? makeSlug(input.slug) : makeSlug(input.title);
  const finalSlug = await uniqueSlug(baseSlug);
  const now = new Date();
  return prisma.page.create({
    data: {
      slug: finalSlug,
      title: input.title,
      content: input.content,
      status: input.status,
      publishedAt: input.status === "published" ? input.publishedAt ?? now : null,
      metaTitle: input.metaTitle ?? null,
      metaDesc: input.metaDesc ?? null,
      metaKeywords: input.metaKeywords ?? null,
      ogImage: input.ogImage ?? null,
      canonicalUrl: input.canonicalUrl ?? null,
      noIndex: input.noIndex ?? false,
      showInFooter: input.showInFooter ?? false,
      footerOrder: input.footerOrder ?? 0,
      authorId: input.authorId ?? null,
    },
  });
}

export async function updatePage(id: string, input: PageInput) {
  const existing = await prisma.page.findUnique({ where: { id } });
  if (!existing) throw new Error("Page not found");

  const baseSlug = input.slug ? makeSlug(input.slug) : existing.slug;
  const finalSlug = baseSlug === existing.slug ? existing.slug : await uniqueSlug(baseSlug, id);

  const wasPublished = existing.status === "published";
  const willPublish = input.status === "published";

  return prisma.page.update({
    where: { id },
    data: {
      slug: finalSlug,
      title: input.title,
      content: input.content,
      status: input.status,
      publishedAt:
        willPublish && !wasPublished
          ? input.publishedAt ?? new Date()
          : !willPublish
            ? null
            : existing.publishedAt,
      metaTitle: input.metaTitle ?? null,
      metaDesc: input.metaDesc ?? null,
      metaKeywords: input.metaKeywords ?? null,
      ogImage: input.ogImage ?? null,
      canonicalUrl: input.canonicalUrl ?? null,
      noIndex: input.noIndex ?? false,
      showInFooter: input.showInFooter ?? false,
      footerOrder: input.footerOrder ?? 0,
    },
  });
}

export async function deletePage(id: string) {
  const page = await prisma.page.findUnique({ where: { id }, select: { isSystem: true } });
  if (!page) throw new Error("Page not found");
  if (page.isSystem) throw new Error("Không thể xoá page hệ thống.");
  return prisma.page.delete({ where: { id } });
}

export async function getPublishedPage(slug: string) {
  return prisma.page.findFirst({
    where: { slug, status: "published" },
    select: {
      id: true,
      slug: true,
      title: true,
      content: true,
      publishedAt: true,
      updatedAt: true,
      metaTitle: true,
      metaDesc: true,
      metaKeywords: true,
      ogImage: true,
      canonicalUrl: true,
      noIndex: true,
      jsonLd: true,
    },
  });
}

export async function listFooterPages() {
  return prisma.page.findMany({
    where: { status: "published", showInFooter: true },
    orderBy: [{ footerOrder: "asc" }, { title: "asc" }],
    select: { slug: true, title: true },
  });
}
