// POST /api/processes/definitions/validate  — dry-run validate, no DB write.
//
// Powers the JSON editor's "Validate" button and the agent retry loop. Returns
// structured errors + warnings + normalized spec so callers can show inline
// feedback before committing.

import { validateWorkflowSpec } from '../../../../../lib/process/spec-validator.js';
import { requireSession } from '../../../../../lib/auth.js';
import { getDb } from '../../../../../lib/db.js';
import { loadKnownAgentTemplates } from '../../../../../lib/process/util.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return Response.json({ ok: false, error: 'invalid_json' }, { status: 400 });
  }

  try {
    // Any signed-in user can dry-run validate (this is read-only and the spec
    // body comes from the user themselves). The 400 path also catches obvious
    // garbage early.
    await requireSession(req);

    const spec = body?.spec;
    if (!spec || typeof spec !== 'object') {
      return Response.json({ ok: false, error: 'spec_required' }, { status: 400 });
    }

    const result = validateWorkflowSpec(spec, { knownAgentTemplates: loadKnownAgentTemplates(getDb()) });
    return Response.json({
      ok: result.ok,
      errors: result.errors,
      warnings: result.warnings,
      normalized: result.normalized,
    });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ ok: false, error: err.error || 'unauthorized' }, { status: err.status });
    }
    return Response.json({ ok: false, error: err?.message || 'server_error' }, { status: 500 });
  }
}
