// GET  /api/processes/definitions      — list definitions (filter by status)
// POST /api/processes/definitions      — create a new definition from a JSON spec
//
// POST validates via lib/process/spec-validator and writes through
// upsertDefinition with author provenance. Returns 201 on success, 400 on
// schema rejection, 409 on slug conflict.

import {
  listDefinitions,
  getDefinition,
  upsertDefinition,
} from '../../../../lib/process/definitions.js';
import { requireSession } from '../../../../lib/auth.js';

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

function requireAdmin(session) {
  if (session.role !== 'admin' && session.role !== 'owner') {
    throw { status: 403, error: 'forbidden' };
  }
}

export async function GET(req) {
  const { searchParams } = new URL(req.url);
  const definitions = listDefinitions({ status: searchParams.get('status') || 'published' });
  return Response.json({ definitions });
}

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

  try {
    const session = await requireSession(req);
    requireAdmin(session);

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

    // Slug conflict check before write — agents creating workflows must not
    // silently overwrite existing definitions. Updates flow through PUT.
    if (spec.slug && getDefinition(spec.slug)) {
      return Response.json(
        { ok: false, error: 'slug_in_use', slug: spec.slug },
        { status: 409 }
      );
    }

    const def = upsertDefinition(spec, {
      source_spec_json: JSON.stringify(spec),
      created_by_user_id: session.user_id || null,
    });

    return Response.json(
      { ok: true, slug: def.slug, version: def.version, definition_id: def.id },
      { status: 201 }
    );
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ ok: false, error: err.error || 'unauthorized' }, { status: err.status });
    }
    if (err?.code === 'spec_invalid') {
      return Response.json({ ok: false, error: 'spec_invalid', errors: err.errors }, { status: 400 });
    }
    if (err?.code === 'version_bump_required') {
      return Response.json({ ok: false, error: 'version_bump_required', message: err.message }, { status: 409 });
    }
    return Response.json({ ok: false, error: err?.message || 'server_error' }, { status: 500 });
  }
}
