import { prisma } from "@/lib/db";
import type { Post, Tag } from "@prisma/client";
export { formatDate } from "@/lib/types";

export type PostWithTags = Post & {
  tags: { tag: Tag }[];
};

export async function getAllPosts(locale: string): Promise<PostWithTags[]> {
  return prisma.post.findMany({
    where: { locale },
    include: { tags: { include: { tag: true } } },
    orderBy: { publishedAt: "desc" },
  });
}

export async function getPostsByCategory(locale: string, category: string): Promise<PostWithTags[]> {
  return prisma.post.findMany({
    where: { locale, category },
    include: { tags: { include: { tag: true } } },
    orderBy: { publishedAt: "desc" },
  });
}

export async function getFeaturedPosts(locale: string, limit = 4): Promise<PostWithTags[]> {
  return prisma.post.findMany({
    where: { locale, featured: true },
    include: { tags: { include: { tag: true } } },
    orderBy: { publishedAt: "desc" },
    take: limit,
  });
}

export async function getPostBySlug(slug: string): Promise<PostWithTags | null> {
  return prisma.post.findUnique({
    where: { slug },
    include: { tags: { include: { tag: true } } },
  });
}

export async function getRelatedPosts(
  locale: string,
  category: string,
  excludeSlug: string,
  limit = 3
): Promise<PostWithTags[]> {
  return prisma.post.findMany({
    where: { locale, category, NOT: { slug: excludeSlug } },
    include: { tags: { include: { tag: true } } },
    orderBy: { publishedAt: "desc" },
    take: limit,
  });
}

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

export async function getLatestPosts(locale: string, limit = 5): Promise<PostWithTags[]> {
  return prisma.post.findMany({
    where: { locale },
    include: { tags: { include: { tag: true } } },
    orderBy: { publishedAt: "desc" },
    take: limit,
  });
}

export function estimateReadTime(html: string): number {
  const text = html.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
  const words = text.split(" ").filter(Boolean).length;
  return Math.max(1, Math.ceil(words / 200));
}
