import prisma from '$lib/server/prisma';
//import { m } from 'bee-agent-framework/serializer-VYDhdryk';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ params, locals }) => {
  const id = Number(params.id);
   console.log('[product load] params.id:', params.id, 'parsed id:', id);

  try {
    // find published product by id
    const product = await prisma.product.findFirst({
      where: { id, isPublished: true },
      include: { Image: true, categories: true }
    });
    console.log('[product load] found product:', product ? { id: product.id, isPublished: product.isPublished } : null);

    if (!product) return { status: 404, error: 'Product not found' };

    // fetch published product documents metadata (include related secure Document FK and metadata)
    const productDocuments = await prisma.productDocument.findMany({
      where: { productId: product.id, isPublished: true },
      select: {
        id: true,
        originalName: true,
        storedName: true,
        mimeType: true,
        sizeBytes: true,
        pageCount: true,
        sortOrder: true,
        isPublished: true,
        purchasePrice: true,
        documentId: true, // FK to secure Document (nullable)
        document: { select: { id: true, pageCount: true } } // relation (lowercase)
      },
      orderBy: { sortOrder: 'asc' }
    });

    // determine entitlements for the current user (if any)
    const entitled = new Set<number>();
    if (locals.user?.id) {
      const now = new Date();

      // build list of document ids to check against Entitlement.documentId
      // include linked secure Document ids (documentId) and also productDocument ids as a fallback
      const docIds = productDocuments.map((d) => d.documentId).filter(Boolean) as number[];
      const pdIds = productDocuments.map((d) => d.id).filter(Boolean) as number[];
      const lookupIds = Array.from(new Set([...docIds, ...pdIds]));

      if (lookupIds.length > 0) {
        const ent = await prisma.entitlement.findMany({
          where: {
            userId: locals.user.id,
            documentId: { in: lookupIds },
            OR: [{ expiresAt: null }, { expiresAt: { gt: now } }]
          },
          select: { documentId: true }
        });
        ent.forEach((e) => entitled.add(e.documentId));
      }
    }

    const docs = productDocuments.map((d) => ({
      ...d,
      // accessible if user subscribed OR entitlement exists for secure Document (documentId) or productDocument id (fallback)
      isAccessible:
        !!locals.isSubscribed ||
        (d.documentId ? entitled.has(d.documentId) : false) ||
        entitled.has(d.id),
        purchasePrice:
        (product as any).digitalCopyPrice ??
        (d as any).purchasePrice ??
        Math.round(product.price * 0.5) // default to 50% of product price
    }));

    // promotions placeholder
    const promotions: any[] = [];

    let discountedPrice: number | null = null;
    let appliedPromotion: any = null;
    for (const promo of promotions) {
      let final = product.price;
      if (promo.discountType === 'PERCENT') final = Math.max(0, product.price * (1 - Number(promo.discountValue) / 100));
      else final = Math.max(0, product.price - Number(promo.discountValue));
      if (discountedPrice === null || final < discountedPrice - 0.0001) {
        discountedPrice = final;
        appliedPromotion = promo;
      }
    }

    return {
      product: {
        ...product,
        discountedPrice: discountedPrice !== null ? Number(discountedPrice.toFixed(2)) : null,
        appliedPromotion
      },
      productDocuments: docs,
      isSubscribed: !!locals.isSubscribed
    };
  } catch (e) {
    console.error('err getting product:', e);
    // @ts-ignore
    return { status: 500, error: (e as any)?.message ?? String(e) };
  }
};