import { NextResponse } from 'next/server';
import mongoose from 'mongoose';
import connectToDatabase from '@/lib/db';
import DemoModel from '@/lib/models/demo';

export const runtime = 'nodejs';

// This is a special identifier for the document that holds the master list of available demo slots.
const DEMO_SLOT_HOLDER_ID = '__DEMO_SLOT_HOLDER__';

export async function GET(request: Request) {
  try {
    await connectToDatabase();
    const Demo = mongoose.models.demos || DemoModel(mongoose);

    // Find the special document that acts as a container for all available demo slots.
    const slotHolder = await Demo.findOne({ name: DEMO_SLOT_HOLDER_ID });

    if (!slotHolder || !slotHolder.slotsEnabled) {
      // If the holder doesn't exist or has slots disabled, return an empty array.
      return NextResponse.json({ success: true, data: [] }, { status: 200 });
    }

    // Filter out slots that are not 'available' or are in the past.
    const availableSlots = slotHolder.slots.filter((slot: any) => {
      if (slot.status !== 'available') {
        return false;
      }
      // Combine date and startTime to create a Date object for comparison.
      // This assumes slot.date is in 'YYYY-MM-DD' format and startTime is 'HH:mm'.
      const slotDateTime = new Date(`${slot.date}T${slot.startTime}`);
      return slotDateTime > new Date(); // Only return future slots.
    });

    return NextResponse.json({ success: true, data: availableSlots }, { status: 200 });

  } catch (error) {
    console.error('Error fetching demo slots:', error);
    return NextResponse.json(
      { error: 'Failed to fetch demo slots. Please try again later.' },
      { status: 500 }
    );
  }
}
