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

/**
 * POST /api/stripe/connect/login-link
 * Creates a one-time login link to the Stripe Express Dashboard for the current user's
 * connected account. Returns { url } for redirect.
 */
export async function POST() {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    if (!stripe) {
      return NextResponse.json(
        { error: "Stripe is not configured" },
        { status: 503 },
      );
    }

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

    if (!user?.stripeConnectAccountId) {
      return NextResponse.json(
        { error: "No Connect account linked" },
        { status: 400 },
      );
    }

    const loginLink = await stripe.accounts.createLoginLink(
      user.stripeConnectAccountId,
    );

    return NextResponse.json({ url: loginLink.url });
  } catch (error) {
    logger.error(
      { err: error, action: "stripe_connect_login_link" },
      "Failed to create Connect login link",
    );
    return NextResponse.json(
      { error: "Failed to create dashboard link" },
      { status: 500 },
    );
  }
}
