// GET    /api/processes/definitions/[slug]  — return def + stages + source_spec
// PUT    /api/processes/definitions/[slug]  — update (bumps version on structural change)
// DELETE /api/processes/definitions/[slug]  — archive (soft delete; never hard-deletes)

import {
  getDefinition,
  listStages,
  upsertDefinition,
  archiveDefinition,
} 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, { params }) {
  const { slug } = await params;
  const definition = getDefinition(slug);
  if (!definition) return Response.json({ error: 'definition_not_found' }, { status: 404 });
  const stages = listStages(definition.id);
  return Response.json({
    definition,
    stages,
    intake_form_schema: definition.intake_form_schema || null,
    source_spec: definition.source_spec || null,
  });
}

export async function PUT(req, { params }) {
  const { slug } = await params;
  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 existing = getDefinition(slug);
    if (!existing) return Response.json({ ok: false, error: 'not_found' }, { status: 404 });

    const spec = body?.spec;
    if (!spec || typeof spec !== 'object') {
      return Response.json({ ok: false, error: 'spec_required' }, { status: 400 });
    }
    if (spec.slug && spec.slug !== slug) {
      return Response.json({ ok: false, error: 'slug_mismatch', expected: slug }, { status: 400 });
    }
    // Force the slug to match the path so an agent can't rename out from under itself.
    spec.slug = slug;

    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 });
  } 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 });
  }
}

export async function DELETE(req, { params }) {
  const { slug } = await params;
  try {
    const session = await requireSession(req);
    requireAdmin(session);

    const result = archiveDefinition(slug);
    if (!result.ok && result.error === 'not_found') {
      return Response.json({ ok: false, error: 'not_found' }, { status: 404 });
    }
    if (!result.ok && result.error === 'in_flight_cases') {
      return Response.json(
        { ok: false, error: 'in_flight_cases', in_flight_cases: result.in_flight_cases },
        { status: 409 }
      );
    }
    return Response.json({ ok: true, archived: true });
  } 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 });
  }
}
