/**
 * PUT /api/ticket-workflows/:id/steps - Replace all steps (bulk update)
 */

import { NextRequest, NextResponse } from 'next/server';
import { postgresClient } from '@/lib/services/postgres-client';
import { TicketWorkflowStep } from '@/lib/types/ticket-workflow';

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await request.json();
    const { steps } = body;

    if (!Array.isArray(steps)) {
      return NextResponse.json(
        { error: 'Invalid request: steps must be an array' },
        { status: 400 }
      );
    }

    // Use transaction to replace all steps
    await postgresClient.transaction(async (client) => {
      // Delete existing steps
      await client.query('DELETE FROM ticket_workflow_steps WHERE workflow_id = $1', [id]);

      // Insert new steps
      for (const step of steps) {
        await client.query(
          `INSERT INTO ticket_workflow_steps
           (workflow_id, step_order, step_type, name, config, on_failure, skip_to_step, is_active, condition)
           VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
          [
            id,
            step.step_order,
            step.step_type,
            step.name,
            JSON.stringify(step.config || {}),
            step.on_failure || 'continue',
            step.skip_to_step || null,
            step.is_active !== undefined ? step.is_active : true,
            step.condition ? JSON.stringify(step.condition) : null
          ]
        );
      }
    });

    // Fetch updated steps
    const result = await postgresClient.query<TicketWorkflowStep>(
      `SELECT * FROM ticket_workflow_steps WHERE workflow_id = $1 ORDER BY step_order`,
      [id]
    );

    return NextResponse.json({ steps: result.rows });
  } catch (error) {
    console.error('[API] Error updating workflow steps:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to update steps' },
      { status: 500 }
    );
  }
}
