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

export async function PUT(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const { valid, error } = validateRequest(request);
    if (!valid) {
      return NextResponse.json({ success: false, error }, { status: 401 });
    }

    await connectToDatabase();
    const data = await request.json();
    const updated = await ScheduleBlock.findByIdAndUpdate(
      params.id,
      { $set: data },
      { new: true, runValidators: true }
    );

    if (!updated) {
      return NextResponse.json(
        { success: false, error: 'Block not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({ success: true, data: updated });
  } catch (error: Error | unknown) {
    return NextResponse.json(
      { success: false, error: error instanceof Error ? error.message : 'Failed to process request' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const { valid, error } = validateRequest(request);
    if (!valid) {
      return NextResponse.json({ success: false, error }, { status: 401 });
    }

    await connectToDatabase();
    const deleted = await ScheduleBlock.findByIdAndDelete(params.id);

    if (!deleted) {
      return NextResponse.json(
        { success: false, error: 'Block not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({ success: true, data: { id: params.id } });
  } catch (error: Error | unknown) {
    return NextResponse.json(
      { success: false, error: error instanceof Error ? error.message : 'Failed to process request' },
      { status: 500 }
    );
  }
}
