import { NextResponse } from 'next/server';
import connectToDatabase from '@/lib/mongodb';
import ScheduleBlock from '@/models/ScheduleBlock';

export async function GET() {
  try {
    await connectToDatabase();
    const blocks = await ScheduleBlock.find().sort({ dayOfWeek: 1, startTime: 1 });
    return NextResponse.json(blocks);
  } catch (error: Error | unknown) {
    return NextResponse.json({ error: error instanceof Error ? error.message : 'Failed to process request' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    await connectToDatabase();
    const data = await request.json();
    
    // Clear existing for a fresh save or handle individually
    // Assuming the user sends the full week schedule on save
    if (Array.isArray(data)) {
      await ScheduleBlock.deleteMany({});
      const newBlocks = await ScheduleBlock.insertMany(data);
      return NextResponse.json(newBlocks);
    } else {
      const block = new ScheduleBlock(data);
      await block.save();
      return NextResponse.json(block);
    }
  } catch (error: Error | unknown) {
    return NextResponse.json({ error: error instanceof Error ? error.message : 'Failed to process request' }, { status: 500 });
  }
}
