import "server-only";
import { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import type { Locale } from "@/lib/i18n/config";
import type { CatalogSearch } from "@/lib/search-params";

export const PAGE_SIZE = 12;

export const productCardInclude = {
  images: { orderBy: { position: "asc" } },
  translations: true,
  category: { include: { translations: true } },
  variants: { orderBy: { position: "asc" } },
} satisfies Prisma.ProductInclude;

export type ProductCard = Prisma.ProductGetPayload<{ include: typeof productCardInclude }>;

export const productDetailInclude = {
  ...productCardInclude,
  reviews: { orderBy: { createdAt: "desc" }, take: 8 },
} satisfies Prisma.ProductInclude;

export type ProductDetail = Prisma.ProductGetPayload<{ include: typeof productDetailInclude }>;

type Translation = { locale: string };

export function translationFor<T extends Translation>(translations: T[], locale: string): T | undefined {
  return (
    translations.find((item) => item.locale === locale) ??
    translations.find((item) => item.locale === "fr") ??
    translations[0]
  );
}

export function productTranslation(product: { translations: ProductTranslationLike[] }, locale: string) {
  return translationFor(product.translations, locale);
}

type ProductTranslationLike = {
  locale: string;
  name: string;
  shortDescription: string;
  description: string;
  materials: string;
  dimensions: string;
  origin: string;
  artisanName: string;
  artisanBio: string;
  care: string;
};

export function productTitle(product: { translations: ProductTranslationLike[] }, locale: string) {
  return productTranslation(product, locale)?.name ?? "";
}

export function productImage(product: { images: { url: string; alt: string }[]; translations: ProductTranslationLike[] }, locale: string) {
  return product.images[0] ? { url: product.images[0].url, alt: product.images[0].alt || productTitle(product, locale) } : null;
}

export function categoryTitle(
  category: { translations: { locale: string; name: string; description: string }[] },
  locale: string,
) {
  return translationFor(category.translations, locale)?.name ?? "";
}

export function categoryDescription(
  category: { translations: { locale: string; name: string; description: string }[] },
  locale: string,
) {
  return translationFor(category.translations, locale)?.description ?? "";
}

export async function getCategories() {
  return prisma.category.findMany({
    where: { isActive: true },
    orderBy: { position: "asc" },
    include: {
      translations: true,
      _count: { select: { products: { where: { isPublished: true } } } },
    },
  });
}

export type CategoryWithMeta = Awaited<ReturnType<typeof getCategories>>[number];

export async function getCategoryBySlug(slug: string) {
  return prisma.category.findFirst({
    where: { slug, isActive: true },
    include: { translations: true, _count: { select: { products: { where: { isPublished: true } } } } },
  });
}

function orderByFor(sort: CatalogSearch["sort"]): Prisma.ProductOrderByWithRelationInput[] {
  switch (sort) {
    case "new":
      return [{ createdAt: "desc" }];
    case "price-asc":
      return [{ price: "asc" }];
    case "price-desc":
      return [{ price: "desc" }];
    case "best-selling":
      return [{ salesCount: "desc" }, { createdAt: "desc" }];
    default:
      return [{ isFeatured: "desc" }, { salesCount: "desc" }, { createdAt: "desc" }];
  }
}

export async function getProducts(search: CatalogSearch) {
  const where: Prisma.ProductWhereInput = { isPublished: true };

  if (search.category) where.category = { slug: search.category, isActive: true };
  if (search.inStock) where.stock = { gt: 0 };
  if (search.featured) where.isFeatured = true;
  if (search.min !== undefined || search.max !== undefined) {
    where.price = {};
    if (search.min !== undefined) where.price.gte = search.min;
    if (search.max !== undefined) where.price.lte = search.max;
  }
  if (search.q) {
    where.OR = [
      { translations: { some: { name: { contains: search.q } } } },
      { translations: { some: { shortDescription: { contains: search.q } } } },
      { sku: { contains: search.q } },
    ];
  }

  const page = search.page;
  const skip = (page - 1) * PAGE_SIZE;

  const [items, total] = await Promise.all([
    prisma.product.findMany({
      where,
      include: productCardInclude,
      orderBy: orderByFor(search.sort),
      skip,
      take: PAGE_SIZE,
    }),
    prisma.product.count({ where }),
  ]);

  return {
    items,
    total,
    page,
    pageSize: PAGE_SIZE,
    totalPages: Math.max(1, Math.ceil(total / PAGE_SIZE)),
  };
}

export async function getFeaturedProducts(limit = 8) {
  return prisma.product.findMany({
    where: { isPublished: true, isFeatured: true },
    include: productCardInclude,
    orderBy: [{ salesCount: "desc" }, { createdAt: "desc" }],
    take: limit,
  });
}

export async function getBestSellers(limit = 4) {
  return prisma.product.findMany({
    where: { isPublished: true },
    include: productCardInclude,
    orderBy: [{ salesCount: "desc" }, { createdAt: "desc" }],
    take: limit,
  });
}

export async function getNewArrivals(limit = 4) {
  return prisma.product.findMany({
    where: { isPublished: true },
    include: productCardInclude,
    orderBy: { createdAt: "desc" },
    take: limit,
  });
}

export async function getProductBySlug(slug: string): Promise<ProductDetail | null> {
  return prisma.product.findFirst({
    where: { slug, isPublished: true },
    include: productDetailInclude,
  });
}

export async function getRelatedProducts(productId: string, categoryId: string, limit = 4) {
  return prisma.product.findMany({
    where: { id: { not: productId }, categoryId, isPublished: true },
    include: productCardInclude,
    orderBy: [{ salesCount: "desc" }, { createdAt: "desc" }],
    take: limit,
  });
}

export async function getProductsByCategorySlug(slug: string, _locale: Locale) {
  return prisma.product.findMany({
    where: { isPublished: true, category: { slug, isActive: true } },
    include: productCardInclude,
    orderBy: [{ isFeatured: "desc" }, { salesCount: "desc" }],
    take: 24,
  });
}

export async function getJournalArticles(limit = 6) {
  return prisma.journalArticle.findMany({
    where: { isPublished: true },
    include: { translations: true },
    orderBy: { publishedAt: "desc" },
    take: limit,
  });
}

export async function getJournalArticle(slug: string) {
  return prisma.journalArticle.findFirst({
    where: { slug, isPublished: true },
    include: { translations: true },
  });
}

export async function getWishlistProducts(userId: string) {
  const wishlist = await prisma.wishlist.findUnique({
    where: { userId },
    include: {
      items: {
        orderBy: { createdAt: "desc" },
        include: { product: { include: productCardInclude } },
      },
    },
  });
  return wishlist?.items.map((item) => item.product).filter((product) => product.isPublished) ?? [];
}

export async function getWishlistProductIds(userId: string) {
  const items = await prisma.wishlistItem.findMany({
    where: { wishlist: { userId } },
    select: { productId: true },
  });
  return items.map((item) => item.productId);
}

export async function getFeaturedCategoriesWithImages() {
  return prisma.category.findMany({
    where: { isActive: true },
    orderBy: { position: "asc" },
    include: { translations: true },
    take: 8,
  });
}
