/**
 * GET /api/integrations/github/repos
 *
 * Returns the connected user's GitHub repos for the import-flow picker.
 * Server-side: never exposes the raw token, only the public repo
 * metadata the picker needs (name, full_name, description, language,
 * is-private, last-pushed, default branch, html_url).
 *
 * 200 → { connected: true, login, repos: [...] }
 * 200 → { connected: false }   ← user hasn't linked GitHub yet
 * 401 → unauthorized
 */

import { NextResponse } from "next/server";
import { authSession } from "@/lib/auth/session-server";
import { loadGithubIntegration, listUserRepos } from "@/lib/integrations/github";

export async function GET() {
  const session = await authSession();
  if (!session?.user?.email) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const link = await loadGithubIntegration(session.user.email);
  if (!link) {
    return NextResponse.json({ connected: false });
  }

  try {
    const repos = await listUserRepos(link.token);
    return NextResponse.json({
      connected: true,
      login: link.login,
      repos: repos.map(r => ({
        id: r.id,
        name: r.name,
        fullName: r.full_name,
        description: r.description,
        defaultBranch: r.default_branch,
        htmlUrl: r.html_url,
        private: r.private,
        language: r.language,
        pushedAt: r.pushed_at,
        fork: r.fork,
      })),
    });
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : "Failed to list repos" },
      { status: 502 },
    );
  }
}
