/**
 * POST /api/projects/clone
 *
 *   Body: { name?: string }
 *
 * Trigger the same auto-clone path the pipeline orchestrator uses: tries to
 * clone the GitLab connector's default_project_path under projectRoots[0]
 * (or ~/IdeaProjects), refreshes projectRoots, and returns the resolved
 * project. Used by the onboarding wizard's empty-state banner and by the
 * chat UI when a pipeline fails with "Project not found".
 */

import { NextResponse } from 'next/server';
import { resolveOrCloneProject, getDefaultCloneRoot } from '@/lib/projects';
import { getInstalledConnector } from '@/lib/connectors/registry';

export async function POST(req: Request) {
  let body: any = {};
  try { body = await req.json(); } catch { /* empty body is fine */ }
  const name = typeof body?.name === 'string' ? body.name.trim() : '';

  const r = resolveOrCloneProject(name);
  // Scratch fallback isn't really a "success" for the caller — they asked for
  // a real clone. Surface why we couldn't do it so the UI can prompt the user
  // to fix the underlying gap (e.g. set gitlab default_project_path).
  if (r.source === 'scratch') {
    const gl = getInstalledConnector('gitlab');
    const path = String(gl?.config?.default_project_path || '').trim();
    const base = String(gl?.config?.base_url || '').trim();
    const reason = !gl ? 'gitlab_connector_missing'
      : !path ? 'gitlab_default_project_path_missing'
      : !base ? 'gitlab_base_url_missing'
      : 'clone_failed';
    return NextResponse.json({
      ok: false,
      reason,
      fallback_project: { name: r.project.name, path: r.project.path },
      target_root: getDefaultCloneRoot(),
      hint: reason === 'clone_failed'
        ? 'git clone failed — see server log. Pipelines will still run inside <dataDir>/scratch as a fallback.'
        : 'set gitlab default_project_path under Settings → Connectors → gitlab; meanwhile pipelines run inside <dataDir>/scratch.',
    }, { status: 200 });
  }

  return NextResponse.json({
    ok: true,
    project: { name: r.project.name, path: r.project.path },
    source: r.source,
    clone_url: r.clone_url,
  });
}
