import type { LayoutServerLoad } from './$types';
import prisma from '$lib/server/prisma';
import { redirect } from '@sveltejs/kit';

export const load = (async ({ locals: { user }, url: { pathname } }) => {
	// If homepage, redirect to product
	if (pathname === '/') redirect(303, '/product');

	// If user is logged in
	if (user) {
		const loggedInUser = await prisma.user.findUnique({
			where: { id: user.id }
		});

		// 🔍 Check if user has an active subscription
		const activeSubscription = await prisma.userSubscription.findFirst({
			where: {
				userId: user.id,
				status: 'ACTIVE',
				isActive: true,
				endsAt: {
					gte: new Date() // still valid
				}
			},
			select: { id: true }
		});

		const isSubscribed = !!activeSubscription;

		// ✅ Return both user and subscription status
		return {
			user: loggedInUser,
			isSubscribed
		};
	}

	// If no user
	return { user: null, isSubscribed: false };
}) satisfies LayoutServerLoad;
