/**
 * POST /api/workspaces/[slug]/provision — (re)run Coolify + Gitea provisioning
 *
 * Idempotent. Useful when initial provisioning during signin or first
 * project create failed because Coolify or Gitea was unavailable.
 */

import { NextResponse } from 'next/server';
import { requireWorkspacePrincipal } from '@/lib/auth/workspace-auth';
import { ensureWorkspaceProvisioned } from '@/lib/workspaces';

export async function POST(
  request: Request,
  { params }: { params: Promise<{ slug: string }> }
) {
  const { slug } = await params;
  const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
  if (principal instanceof NextResponse) return principal;

  const updated = await ensureWorkspaceProvisioned(principal.workspace);

  return NextResponse.json({
    slug: updated.slug,
    coolifyProjectUuid: updated.coolify_project_uuid,
    giteaOrg: updated.gitea_org,
    provisionStatus: updated.provision_status,
    provisionError: updated.provision_error,
  });
}
