import { NextRequest, NextResponse } from "next/server";
import type { Prisma } from "@prisma/client";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

/**
 * PATCH /api/dashboard/devices/[id]
 *
 * Update device settings (marketplace opt-in, price). Session auth.
 */
export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const body = await req.json().catch(() => ({}));
  const { marketplace_enabled, price_cents_per_hour, operator_agreement_accepted } = body;

  try {
    const device = await db.device.findFirst({
      where: { id, userId: session.user.id },
      include: { user: { select: { marketplaceTermsAcceptedAt: true } } },
    });
    if (!device) {
      return NextResponse.json({ error: "Device not found" }, { status: 404 });
    }

    // When enabling marketplace, require operator agreement acceptance (#304)
    if (marketplace_enabled === true) {
      const alreadyAccepted = device.user.marketplaceTermsAcceptedAt != null;
      const acceptedNow = operator_agreement_accepted === true;
      if (!alreadyAccepted && !acceptedNow) {
        return NextResponse.json(
          { error: "Operator agreement must be accepted before listing on the marketplace", code: "OPERATOR_AGREEMENT_REQUIRED" },
          { status: 400 }
        );
      }
      if (acceptedNow && !alreadyAccepted) {
        await db.user.update({
          where: { id: session.user.id },
          data: { marketplaceTermsAcceptedAt: new Date() },
        });
      }
    }

    const data: Prisma.DeviceUpdateInput = {};
    if (typeof marketplace_enabled === "boolean") {
      data.marketplaceEnabled = marketplace_enabled;
    }
    if (price_cents_per_hour !== undefined) {
      data.marketplacePriceCents =
        price_cents_per_hour === null || price_cents_per_hour === ""
          ? null
          : Math.max(0, Math.round(Number(price_cents_per_hour)));
    }

    if (Object.keys(data).length === 0) {
      return NextResponse.json({
        id: device.id,
        name: device.name,
        marketplace_enabled: device.marketplaceEnabled,
        price_cents_per_hour: device.marketplacePriceCents,
      });
    }

    const updated = await db.device.update({
      where: { id },
      data,
    });

    return NextResponse.json({
      id: updated.id,
      name: updated.name,
      marketplace_enabled: updated.marketplaceEnabled,
      price_cents_per_hour: updated.marketplacePriceCents,
    });
  } catch {
    return NextResponse.json(
      { error: "Failed to update device" },
      { status: 500 }
    );
  }
}
