import { NextRequest, NextResponse } from "next/server";
import { getOAuthClient, getSession } from "@/auth";

function getBaseUrl(request: NextRequest): string {
  const host =
    request.headers.get("x-forwarded-host") ||
    request.headers.get("host") ||
    new URL(request.url).host;
  const proto = request.headers.get("x-forwarded-proto") || "https";

  return `${proto}://${host}`;
}

async function handleCallback(request: NextRequest) {
  const baseUrl = getBaseUrl(request);
  const params = new URLSearchParams(request.nextUrl.search);

  // Check for OAuth error
  const error = params.get("error");
  if (error) {
    const description = params.get("error_description") || error;
    return NextResponse.redirect(
      new URL(`/login?error=${encodeURIComponent(description)}`, baseUrl),
    );
  }

  try {
    const client = await getOAuthClient();

    // Complete the OAuth flow
    const { session: oauthSession, state } = await client.callback(params);

    // Parse returnUrl from state
    let returnUrl = "/";
    if (state) {
      try {
        const parsed = JSON.parse(state);
        if (parsed.returnUrl && typeof parsed.returnUrl === "string") {
          returnUrl = parsed.returnUrl;
        }
      } catch {
        // Ignore parse errors
      }
    }

    // Store the DID in our session cookie
    const session = await getSession();

    // If already signed in with different account, sign out old one
    if (session.did && session.did !== oauthSession.did) {
      try {
        const oldSession = await client.restore(session.did);
        if (oldSession) await oldSession.signOut();
      } catch {
        // Ignore errors signing out old session
      }
    }

    session.did = oauthSession.did;
    await session.save();

    // Redirect to returnUrl
    const redirectUrl = new URL(returnUrl, baseUrl);
    return NextResponse.redirect(redirectUrl);
  } catch (err) {
    console.error("OAuth callback error:", err);
    const message = err instanceof Error ? err.message : "Authentication failed";
    return NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(message)}`, baseUrl));
  }
}

export async function GET(request: NextRequest) {
  return handleCallback(request);
}
