import { NextResponse } from "next/server";
import { db } from "@/app/db/db";
import { plan } from "@/app/db/schema/recommendations";
import { eq } from "drizzle-orm";

export async function POST(
  _req: Request,
  context: { params: Promise<{ id: string }> }
) {
  const { id } = await context.params;
  const planId = Number(id);

  if (Number.isNaN(planId)) {
    return NextResponse.json({ error: "Invalid plan id" }, { status: 400 });
  }

  const target = await db.query.plan.findFirst({
    where: eq(plan.id, BigInt(planId)),
    columns: { propertyId: true },
  });

  if (!target) {
    return NextResponse.json({ error: "Plan not found" }, { status: 404 });
  }

  await db.transaction(async (tx) => {
    await tx
      .update(plan)
      .set({ isDefault: false })
      .where(eq(plan.propertyId, target.propertyId));

    await tx
      .update(plan)
      .set({ isDefault: true })
      .where(eq(plan.id, BigInt(planId)));
  });

  return NextResponse.json({ success: true });
}
