export const dynamic = 'force-dynamic';
export const revalidate = 0;

import { NextResponse } from 'next/server';
import { getSql } from '../../../../../lib/db.js';
import { getOrgId } from '../../../../../lib/org.js';
import { apiErrorResponse } from '../../../../../lib/apiErrors.js';
import { duplicateWorkflowTemplate } from '../../../../../lib/repositories/workflow-templates.repository.js';

export async function POST(request, { params }) {
  try {
    const sql = getSql();
    const orgId = getOrgId(request);
    const { templateId } = await params;

    // Accept optional name/slug override in body; tolerate empty body.
    let overrides = {};
    try {
      overrides = (await request.json()) || {};
    } catch {
      overrides = {};
    }

    const duplicate = await duplicateWorkflowTemplate(sql, orgId, templateId, overrides);
    if (!duplicate) {
      return NextResponse.json({ error: 'Source template not found' }, { status: 404 });
    }
    return NextResponse.json({ template: duplicate }, { status: 201 });
  } catch (error) {
    return apiErrorResponse(error, 'WORKFLOW TEMPLATE DUPLICATE');
  }
}
