import { getDefinition } from '@/lib/process/definitions.js';
import { getSettings, upsertSettings, resolveBrandPresentation } from '@/lib/process/definition-settings.js';

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

// GET /api/processes/definitions/<slug>/settings?project_id=<id>&include_brand=1
//
// Returns the (definition, project) settings row, the definition, and
// (when ?include_brand=1) the merged brand the artifact renderer would
// use right now. The merged brand is computed from /settings/brand +
// per-workflow overrides so the drawer can show "what the form will
// actually look like" without duplicating brand fields locally.
export async function GET(req, { params }) {
  const { slug } = await params;
  const url = new URL(req.url);
  const project_id = url.searchParams.get('project_id');
  const includeBrand = url.searchParams.get('include_brand') === '1';
  if (!project_id) return Response.json({ error: 'project_id required' }, { status: 400 });
  const definition = getDefinition(slug);
  if (!definition) return Response.json({ error: 'definition_not_found' }, { status: 404 });
  const settings = getSettings({ definition_id: definition.id, project_id });
  const resolved_brand = includeBrand
    ? resolveBrandPresentation({ settings })
    : undefined;
  return Response.json({ definition, settings, ...(resolved_brand ? { resolved_brand } : {}) });
}

// PUT /api/processes/definitions/<slug>/settings
// Body: { project_id, brand?, agent_overrides?, auto_approve_rules?,
//         share_link_enabled?, share_link_default_expiry_days?,
//         default_for_project?, template_html?, user_id? }
export async function PUT(req, { params }) {
  const { slug } = await params;
  try {
    const body = await req.json();
    if (!body.project_id) {
      return Response.json({ error: 'project_id required' }, { status: 400 });
    }
    const definition = getDefinition(slug);
    if (!definition) return Response.json({ error: 'definition_not_found' }, { status: 404 });
    const settings = upsertSettings({
      definition_id: definition.id,
      project_id: body.project_id,
      default_for_project: body.default_for_project,
      brand: body.brand,
      template_html: body.template_html,
      agent_overrides: body.agent_overrides,
      auto_approve_rules: body.auto_approve_rules,
      share_link_enabled: body.share_link_enabled,
      share_link_default_expiry_days: body.share_link_default_expiry_days,
      user_id: body.user_id || null,
    });
    // Settings rows themselves carry updated_at + created_by_user_id +
    // template_version as the audit trail. No separate audit_logs row is
    // emitted for settings changes — they are pre-execution configuration,
    // not state-machine events.
    return Response.json({ settings });
  } catch (err) {
    return Response.json({ error: err?.message || String(err) }, { status: 400 });
  }
}
