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";

const CONNECT_RETURN_PATH = "/dashboard/devices?connect=return";
const CONNECT_REFRESH_PATH = "/dashboard/devices?connect=refresh";

/**
 * POST /api/stripe/connect/onboard
 * Creates a Stripe Connect Express account for the current user (if none) and returns
 * an account link URL for Connect onboarding. One account per user (operator).
 */
export async function POST() {
  try {
    const session = await auth();

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

    const baseUrl =
      process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
    const returnUrl = `${baseUrl}${CONNECT_RETURN_PATH}`;
    const refreshUrl = `${baseUrl}${CONNECT_REFRESH_PATH}`;

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

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

    if (!user?.email) {
      return NextResponse.json(
        { error: "User or email not found" },
        { status: 404 },
      );
    }

    let accountId = user.stripeConnectAccountId;

    if (!accountId) {
      const account = await stripe.accounts.create({
        type: "express",
        email: user.email,
        metadata: { userId: user.id },
      });
      accountId = account.id;

      await db.user.update({
        where: { id: user.id },
        data: { stripeConnectAccountId: accountId },
      });

      logger.info(
        { action: "stripe_connect_onboard", userId: user.id, accountId },
        "Created Stripe Connect Express account for user",
      );
    }

    const accountLink = await stripe.accountLinks.create({
      account: accountId,
      refresh_url: refreshUrl,
      return_url: returnUrl,
      type: "account_onboarding",
    });

    return NextResponse.json({ url: accountLink.url });
  } catch (error) {
    logger.error(
      { err: error, action: "stripe_connect_onboard" },
      "Failed to create Connect onboarding link",
    );
    return NextResponse.json(
      { error: "Failed to create onboarding link" },
      { status: 500 },
    );
  }
}
