import { NextResponse } from "next/server";
import { getAdminUser } from "@/lib/admin-permissions";
import { savePaymentSettings } from "@/actions/payments";

export async function POST(request: Request) {
  try {
    const form = await request.formData();
    const code = String(form.get("code") ?? "");
    const error = String(form.get("error") ?? "");
    const state = String(form.get("state") ?? "");
    const baseUrl = request.headers.get("origin") ?? new URL(request.url).origin;

    if (error) {
      return NextResponse.redirect(
        new URL(`/admin/settings/payments?stripe_error=${encodeURIComponent(error)}`, baseUrl),
      );
    }
    if (!code) {
      return NextResponse.redirect(
        new URL("/admin/settings/payments?stripe_error=no_code", baseUrl),
      );
    }

    const adminUser = await getAdminUser();
    if (!adminUser || !adminUser.brand_id) {
      return NextResponse.redirect(new URL("/admin/settings/payments?error=unauthorized", baseUrl));
    }
    let brandId = adminUser.brand_id;
    if (state) {
      try {
        const decoded = JSON.parse(Buffer.from(state, "base64").toString());
        if (decoded.brandId) brandId = decoded.brandId;
      } catch {
        // ignore malformed state
      }
    }

    const clientId = process.env.STRIPE_CLIENT_ID;
    const clientSecret = process.env.STRIPE_CLIENT_SECRET;
    if (!clientId || !clientSecret) {
      return NextResponse.redirect(
        new URL("/admin/settings/payments?stripe_error=oauth_not_configured", baseUrl),
      );
    }

    const tokenResponse = await fetch("https://connect.stripe.com/oauth/token", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({
        grant_type: "authorization_code",
        code,
        client_id: clientId,
        client_secret: clientSecret,
      }),
    });
    const tokenData = await tokenResponse.json();

    if (tokenData?.error) {
      return NextResponse.redirect(
        new URL(
          `/admin/settings/payments?stripe_error=${encodeURIComponent(tokenData.error_description || tokenData.error)}`,
          baseUrl,
        ),
      );
    }

    const stripeUserId: string | undefined = tokenData.stripe_user_id;
    const accessToken: string | undefined = tokenData.access_token;
    const publishableKey: string | undefined = tokenData.stripe_publishable_key;

    const result = await savePaymentSettings({
      brandId,
      provider: "stripe",
      stripePublishableKey: publishableKey,
      stripeSecretKey: accessToken,
      stripeUserId,
    });
    if (result.success) {
      return NextResponse.redirect(
        new URL("/admin/settings/payments?stripe_connected=true", baseUrl),
      );
    }
    return NextResponse.redirect(
      new URL(
        `/admin/settings/payments?stripe_error=${encodeURIComponent(result.error || "Failed to save")}`,
        baseUrl,
      ),
    );
  } catch (err) {
    const baseUrl = request.headers.get("origin") ?? new URL(request.url).origin;
    return NextResponse.redirect(
      new URL(
        `/admin/settings/payments?stripe_error=${encodeURIComponent("Failed to complete OAuth")}`,
        baseUrl,
      ),
    );
  }
}

export async function GET() {
  return NextResponse.redirect(new URL("/admin/settings/payments"));
}
