import { NextRequest, NextResponse } from "next/server";

const API_URL = process.env.API_URL || process.env.UNFORGIT_API_URL || "http://localhost:3737";

function decodeJwtPayload(token: string): { isAdmin?: boolean; role?: string } | null {
  try {
    const parts = token.split(".");
    if (parts.length !== 3) return null;
    const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
    return payload;
  } catch {
    return null;
  }
}

export async function GET(request: NextRequest) {
  const authHeader = request.headers.get("authorization");

  if (!authHeader) {
    return NextResponse.json(
      { error: "Unauthorized", message: "Missing Authorization header" },
      { status: 401 }
    );
  }

  const token = authHeader.replace("Bearer ", "");
  const payload = decodeJwtPayload(token);
  const isAdmin = payload?.isAdmin === true || payload?.role === "admin";

  if (isAdmin) {
    const response = await fetch(`${API_URL}/v1/admin/repos`, {
      headers: {
        Authorization: authHeader,
      },
    });

    const data = await response.json();

    if (!response.ok) {
      return NextResponse.json(data, { status: response.status });
    }

    return NextResponse.json(data);
  }

  const meResponse = await fetch(`${API_URL}/v1/auth/me`, {
    headers: {
      Authorization: authHeader,
    },
  });

  if (!meResponse.ok) {
    const data = await meResponse.json();
    return NextResponse.json(data, { status: meResponse.status });
  }

  const meData = await meResponse.json();
  const repos = (meData.repos || []).map((r: { orgId: string; repoId: string }) => ({
    orgId: r.orgId,
    repoId: r.repoId,
    userCount: 1,
    memoryCount: 0,
  }));

  return NextResponse.json({ repos });
}
