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 POST(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 }
      );
    }

    // Update all excursions where section = 'circuits' to set priceMAD = 0
    const result = await Excursion.updateMany(
      { section: 'circuits' },
      { $set: { priceMAD: 0 } }
    );

    return NextResponse.json({
      success: true,
      message: `Successfully updated ${result.modifiedCount} circuits to have priceMAD = 0`,
      modifiedCount: result.modifiedCount
    });
  } catch (error) {
    console.error('Error updating circuits:', error);
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to update circuits'
      },
      { status: 500 }
    );
  }
}
