import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";

/** Minimum price per 1M tokens in dollars. */
const MIN_PRICE = 0.01;
/** Maximum price per 1M tokens in dollars. */
const MAX_PRICE = 1.0;

export async function GET() {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const settings = await db.operatorSettings.findUnique({
      where: { userId: session.user.id },
    });

    if (!settings) {
      return NextResponse.json({
        marketplaceEnabled: false,
        pricePerMToken: 0.1,
        autoPrice: true,
        availableModels: [],
      });
    }

    return NextResponse.json({
      ...settings,
      availableModels: JSON.parse(settings.availableModels || "[]"),
    });
  } catch (error) {
    logger.error({ error }, "operator_settings_get_failed");
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}

export async function PUT(request: Request) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const { marketplaceEnabled, pricePerMToken, autoPrice, availableModels } =
      body;

    // Validate price range ($0.01 - $1.00 per 1M tokens)
    if (pricePerMToken !== undefined) {
      if (
        typeof pricePerMToken !== "number" ||
        !Number.isFinite(pricePerMToken) ||
        pricePerMToken < MIN_PRICE ||
        pricePerMToken > MAX_PRICE
      ) {
        return NextResponse.json(
          {
            error: `pricePerMToken must be between $${MIN_PRICE.toFixed(2)} and $${MAX_PRICE.toFixed(2)}`,
          },
          { status: 400 },
        );
      }
    }

    // Terms gate: require marketplace terms acceptance before enabling
    if (marketplaceEnabled === true) {
      const user = await db.user.findUnique({
        where: { id: session.user.id },
        select: { marketplaceTermsAcceptedAt: true },
      });
      if (!user?.marketplaceTermsAcceptedAt) {
        return NextResponse.json(
          { error: "You must accept marketplace terms before enabling." },
          { status: 403 },
        );
      }
    }

    const settings = await db.operatorSettings.upsert({
      where: { userId: session.user.id },
      create: {
        userId: session.user.id,
        marketplaceEnabled: marketplaceEnabled ?? false,
        pricePerMToken: pricePerMToken ?? 0.1,
        autoPrice: autoPrice ?? true,
        availableModels: JSON.stringify(availableModels ?? []),
      },
      update: {
        ...(marketplaceEnabled !== undefined && { marketplaceEnabled }),
        ...(pricePerMToken !== undefined && { pricePerMToken }),
        ...(autoPrice !== undefined && { autoPrice }),
        ...(availableModels !== undefined && {
          availableModels: JSON.stringify(availableModels),
        }),
      },
    });

    logger.info(
      { userId: session.user.id, marketplaceEnabled: settings.marketplaceEnabled },
      "operator_settings_updated",
    );

    return NextResponse.json({
      ...settings,
      availableModels: JSON.parse(settings.availableModels || "[]"),
    });
  } catch (error) {
    logger.error({ error }, "operator_settings_update_failed");
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}
