import { NextRequest, NextResponse } from "next/server";
import dbConnect from "@/lib/connectdb";
import { DataPlan } from "@/models/dataAirtimeUtil";
import { authOptions } from "@/auth";
import { getServerSession } from "next-auth";

export async function PUT(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session || session.user.role !== "admin") {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    await dbConnect();

    const { ids, available } = await req.json();

    if (!ids || !Array.isArray(ids)) {
      return NextResponse.json(
        { message: "Invalid IDs provided" },
        { status: 400 }
      );
    }

    if (typeof available !== "boolean") {
      return NextResponse.json(
        { message: "Invalid availability status" },
        { status: 400 }
      );
    }

    const result = await DataPlan.updateMany(
      { _id: { $in: ids } },
      { $set: { available } }
    );

    if (result.modifiedCount === 0) {
      return NextResponse.json(
        { message: "No matching plans found to update" },
        { status: 404 }
      );
    }

    return NextResponse.json(
      {
        message: `Successfully updated ${result.modifiedCount} data plans`,
        modifiedCount: result.modifiedCount,
      },
      { status: 200 }
    );
  } catch (error: any) {
    console.error("Error updating data plans availability:", error);
    return NextResponse.json(
      { message: "Internal server error", error: error.message },
      { status: 500 }
    );
  }
}
