import prisma from '$lib/server/prisma';
import type { PageServerLoad } from './$types';
import { LegislationType } from '@prisma/client';

const PAGE_SIZE = 25;

export const load: PageServerLoad = async ({ url, locals: { user } }) => {
	// Only block if user is not logged in at all (subscription check is handled elsewhere)
	if (!user) {
		return {
			legislations: [],
			page: 1,
			totalPages: 0,
			search: '',
			activeType: null,
			statusFilter: null,
			activeYear: null,
			years: [],
			types: Object.values(LegislationType)
		};
	}

	const search = url.searchParams.get('search')?.trim() || '';
	const typeParam = url.searchParams.get('type');
	const statusFilter = url.searchParams.get('status')?.trim() || null;
	const page = Math.max(1, parseInt(url.searchParams.get('page') || '1', 10));

	// Year filter (last 5 years including current)
	const now = new Date();
	const currentYear = now.getFullYear();
	const minYear = currentYear - 4;
	const yearParam = url.searchParams.get('year');
	let activeYear: number | null = null;

	if (yearParam) {
		const parsed = parseInt(yearParam, 10);
		if (!isNaN(parsed) && parsed >= minYear && parsed <= currentYear) {
			activeYear = parsed;
		}
	}
	const years = Array.from({ length: 5 }, (_, i) => currentYear - i);

	const activeType =
		typeParam && Object.values(LegislationType).includes(typeParam as LegislationType)
			? (typeParam as LegislationType)
			: null;

	// Build filters dynamically
	const where: any = {};
	if (activeYear !== null) where.year = activeYear;
	if (activeType) where.type = activeType;
	if (search) {
		where.OR = [
			{ title: { contains: search, mode: 'insensitive' } },
			{ number: { contains: search, mode: 'insensitive' } }
		];
	}
	if (statusFilter) where.statusOnDatabase = { contains: statusFilter, mode: 'insensitive' };

	// Fetch data from legislationItem table
	const total = await prisma.legislationItem.count({ where });
	const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
	const skip = (page - 1) * PAGE_SIZE;

	const legislations = await prisma.legislationItem.findMany({
		where,
		orderBy: { year: 'desc' },
		skip,
		take: PAGE_SIZE
	});

	return {
		legislations,
		page,
		totalPages,
		search,
		activeType,
		statusFilter,
		activeYear,
		years,
		types: Object.values(LegislationType)
	};
};
