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

export const runtime = "nodejs";

/**
 * GET /api/marketplace/terms
 *
 * Returns the current user's marketplace terms acceptance status.
 */
export async function GET() {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const user = await db.user.findUnique({
      where: { id: session.user.id },
      select: { marketplaceTermsAcceptedAt: true },
    });

    const acceptedAt = user?.marketplaceTermsAcceptedAt ?? null;

    return NextResponse.json({
      accepted: acceptedAt !== null,
      acceptedAt: acceptedAt ? acceptedAt.toISOString() : null,
    });
  } catch (error) {
    logger.error({ error }, "marketplace_terms_get_failed");
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}

/**
 * POST /api/marketplace/terms
 *
 * Accepts the marketplace terms for the current user.
 * Sets marketplaceTermsAcceptedAt to the current timestamp.
 */
export async function POST() {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const user = await db.user.update({
      where: { id: session.user.id },
      data: { marketplaceTermsAcceptedAt: new Date() },
      select: { marketplaceTermsAcceptedAt: true },
    });

    logger.info(
      { userId: session.user.id },
      "marketplace_terms_accepted",
    );

    return NextResponse.json({
      accepted: true,
      acceptedAt: user.marketplaceTermsAcceptedAt!.toISOString(),
    });
  } catch (error) {
    logger.error({ error }, "marketplace_terms_accept_failed");
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}
