/**
 * Pipeline Steps API — list and manage steps for a pipeline.
 */

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

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const result = await postgresClient.query(
      `SELECT * FROM pipeline_steps WHERE pipeline_id = $1 ORDER BY step_order`, [id]
    );
    return NextResponse.json({ data: result.rows });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}

export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const body = await request.json();
    const { step_order, step_type, name, config, on_failure, skip_to_step, is_active, timeout_ms } = body;

    if (!step_type || !name) {
      return NextResponse.json({ error: 'step_type and name are required' }, { status: 400 });
    }

    const result = await postgresClient.query(
      `INSERT INTO pipeline_steps (pipeline_id, step_order, step_type, name, config, on_failure, skip_to_step, is_active, timeout_ms)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
       RETURNING *`,
      [id, step_order || 0, step_type, name, JSON.stringify(config || {}), on_failure || 'stop', skip_to_step || null, is_active ?? true, timeout_ms || null]
    );

    return NextResponse.json(result.rows[0], { status: 201 });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}

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: 'steps array is required' }, { status: 400 });
    }

    // Replace all steps for this pipeline
    await postgresClient.query(`DELETE FROM pipeline_steps WHERE pipeline_id = $1`, [id]);

    for (const step of steps) {
      await postgresClient.query(
        `INSERT INTO pipeline_steps (pipeline_id, step_order, step_type, name, config, on_failure, skip_to_step, is_active, timeout_ms)
         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 || 'stop', step.skip_to_step || null, step.is_active ?? true, step.timeout_ms || null]
      );
    }

    const result = await postgresClient.query(
      `SELECT * FROM pipeline_steps WHERE pipeline_id = $1 ORDER BY step_order`, [id]
    );

    return NextResponse.json({ data: result.rows });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
