import { NextResponse } from 'next/server';
import { prisma } from '../../../../../lib/prisma';
import { expandBlockedDates, getCalendarRanges } from '../../../../../lib/calendar';

export async function GET(_: Request, { params }: { params: { id: string } }) {
  const monthParam = Number(new URL(_.url).searchParams.get('month') ?? new Date().getUTCMonth());
  const yearParam = Number(new URL(_.url).searchParams.get('year') ?? new Date().getUTCFullYear());
  const monthsParam = Math.min(Number(new URL(_.url).searchParams.get('months') ?? 1), 12);
  const forceRefresh = new URL(_.url).searchParams.get('refresh') === '1';

  const month = Number.isFinite(monthParam) ? monthParam : new Date().getUTCMonth();
  const year = Number.isFinite(yearParam) ? yearParam : new Date().getUTCFullYear();
  const months = Number.isFinite(monthsParam) && monthsParam > 0 ? monthsParam : 1;

  const listing = await prisma.listing.findUnique({ where: { id: params.id }, select: { calendarUrls: true } });
  if (!listing) {
    return NextResponse.json({ error: 'Listing not found' }, { status: 404 });
  }

  const urls = (listing.calendarUrls ?? []).filter(Boolean);
  if (!urls.length) {
    return NextResponse.json({ blockedDates: [] });
  }

  const start = new Date(Date.UTC(year, month, 1));
  const end = new Date(start);
  end.setUTCMonth(end.getUTCMonth() + months);

  const ranges = await getCalendarRanges(urls, { forceRefresh });
  const blockedDates = expandBlockedDates(ranges, start, end);

  return NextResponse.json({ blockedDates });
}
