/**
 * GET /api/projects/[projectId]/codebases
 *
 * Returns the list of codebases that make up this project, by
 * inspecting the project's Gitea repository:
 *
 *   - If `apps/` exists at the repo root, each subdirectory under
 *     `apps/` is one codebase (Turborepo convention).
 *   - Otherwise, the repo root itself is treated as a single
 *     codebase (typical for non-monorepo projects).
 *   - If no Gitea repo is connected to this project yet, an empty
 *     list is returned with a `reason` field for the UI to render.
 *
 * Response:
 *   { codebases: [{ id, label, path, hint? }], reason?: string }
 */

import { NextResponse } from "next/server";
import { authSession } from "@/lib/auth/session-server";
import { query } from "@/lib/db-postgres";

const GITEA_API_URL = process.env.GITEA_API_URL ?? "https://git.vibnai.com";
const GITEA_API_TOKEN = process.env.GITEA_API_TOKEN ?? "";

interface Codebase {
  id: string;
  label: string;
  path: string;
  hint?: string;
}

interface GiteaItem {
  name: string;
  path: string;
  type: "file" | "dir" | "symlink";
}

async function giteaList(repo: string, path: string): Promise<GiteaItem[] | null> {
  const encoded = path ? encodeURIComponent(path).replace(/%2F/g, "/") : "";
  const res = await fetch(
    `${GITEA_API_URL}/api/v1/repos/${repo}/contents/${encoded}`,
    {
      headers: { Authorization: `token ${GITEA_API_TOKEN}` },
      next: { revalidate: 30 },
    }
  );
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`Gitea ${res.status} listing ${repo}/${path}`);
  const data = await res.json();
  return Array.isArray(data) ? (data as GiteaItem[]) : null;
}

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const session = await authSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const rows = await query<{ data: Record<string, unknown> }>(
      `SELECT p.data FROM fs_projects p
       JOIN fs_users u ON u.id = p.user_id
       WHERE p.id = $1 AND u.data->>'email' = $2 LIMIT 1`,
      [projectId, session.user.email]
    );
    if (rows.length === 0) {
      return NextResponse.json({ error: "Project not found" }, { status: 404 });
    }

    const giteaRepo = rows[0].data?.giteaRepo as string | undefined;
    if (!giteaRepo) {
      return NextResponse.json({
        codebases: [],
        reason: "no_repo",
      });
    }

    // Inspect the repo root. If `apps/` is present, list its
    // subdirectories. Otherwise treat the root as one codebase.
    const root = await giteaList(giteaRepo, "");
    if (!root) {
      return NextResponse.json({
        codebases: [],
        reason: "empty_repo",
      });
    }

    const appsDir = root.find(item => item.type === "dir" && item.name === "apps");
    let codebases: Codebase[] = [];

    if (appsDir) {
      const appsChildren = await giteaList(giteaRepo, "apps");
      if (appsChildren) {
        codebases = appsChildren
          .filter(item => item.type === "dir")
          .map(item => ({
            id: item.name,
            label: item.name,
            path: `apps/${item.name}`,
          }));
      }
    }

    if (codebases.length === 0) {
      // Single-repo project: use the repo's tail name as a friendly
      // label (e.g. "twenty-crm"), root path is "".
      const repoName = giteaRepo.split("/").pop() || "app";
      codebases = [
        {
          id: "root",
          label: repoName,
          path: "",
          hint: "Single-codebase project — repository root.",
        },
      ];
    }

    return NextResponse.json({ codebases });
  } catch (err) {
    console.error("[codebases API]", err);
    return NextResponse.json({ error: "Failed to list codebases" }, { status: 500 });
  }
}
