import { NextRequest, NextResponse } from 'next/server';
import { connectDB } from '@/lib/mongodb';
import { Excursion } from '@/models/Excursion';
import { auth } from '@clerk/nextjs/server';
import User from '@/models/User';

export async function DELETE(request: NextRequest) {
  try {
    const { userId } = await auth();

    if (!userId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    await connectDB();
    const user = await User.findOne({ clerkId: userId });

    // Check if user is admin or super_admin
    if (!user || (user.role !== 'admin' && user.role !== 'super_admin')) {
      return NextResponse.json(
        { error: 'Admin access required' },
        { status: 403 }
      );
    }

    // Delete all excursions where section is NOT 'circuits'
    const result = await Excursion.deleteMany({
      section: { $ne: 'circuits' }
    });

    return NextResponse.json({
      success: true,
      message: `Successfully deleted ${result.deletedCount} non-circuit excursions`,
      deletedCount: result.deletedCount
    });
  } catch (error) {
    console.error('Error deleting non-circuit excursions:', error);
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to delete non-circuit excursions'
      },
      { status: 500 }
    );
  }
}
