// ...existing code...
import type { PageServerLoad } from './$types';
import prisma from '$lib/server/prisma';
import { error, redirect } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ params, locals }) => {
    const productId = Number(params.id);
    const docId = Number(params.docId);

    // require login
    if (!locals.user) throw redirect(303, '/login');

    // ensure product exists and is published
    const product = await prisma.product.findUnique({ where: { id: productId, isPublished: true } });
    if (!product) throw error(404, 'Product not found');

    // fetch the productDocument (published)
    const pd = await prisma.productDocument.findFirst({
        where: { id: docId, productId, isPublished: true },
        select: { id: true, originalName: true, documentId: true, pageCount: true }
    });
    if (!pd) throw error(404, 'Document not found');

    // If user is subscribed allow access
    if (locals.isSubscribed) {
        return { productId, docId: pd.id, title: pd.originalName };
    }

    // Otherwise check entitlement for this user.
    // Entitlement.documentId may store either the secure Document id or the productDocument id (fallback).
    const lookupIds = [pd.documentId, pd.id].filter(Boolean) as number[];
    if (lookupIds.length > 0) {
        const now = new Date();
        const ent = await prisma.entitlement.findFirst({
            where: {
                userId: locals.user.id,
                documentId: { in: lookupIds },
                OR: [{ expiresAt: null }, { expiresAt: { gt: now } }]
            },
            select: { id: true }
        });
        if (ent) {
            return { productId, docId: pd.id, title: pd.originalName };
        }
    }

    // No subscription and no entitlement -> pricing
    throw redirect(303, '/pricing');
};
// ...existing code...