/**
 * Single Pipeline API — get, update, delete a pipeline with its steps.
 */

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 pipelineResult = await postgresClient.query(
      `SELECT * FROM webhook_pipelines WHERE id = $1`, [id]
    );

    if (pipelineResult.rows.length === 0) {
      return NextResponse.json({ error: 'Pipeline not found' }, { status: 404 });
    }

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

    const execResult = await postgresClient.query(
      `SELECT id, status, trigger_source, started_at, completed_at, duration_ms, error_message
       FROM pipeline_executions WHERE pipeline_id = $1 ORDER BY created_at DESC LIMIT 20`, [id]
    );

    return NextResponse.json({
      ...pipelineResult.rows[0],
      steps: stepsResult.rows,
      recent_executions: execResult.rows,
    });
  } 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 { name, description, is_active, trigger_source, trigger_conditions, sort_order } = body;

    const result = await postgresClient.query(
      `UPDATE webhook_pipelines
       SET name = COALESCE($1, name),
           description = COALESCE($2, description),
           is_active = COALESCE($3, is_active),
           trigger_source = COALESCE($4, trigger_source),
           trigger_conditions = COALESCE($5, trigger_conditions),
           sort_order = COALESCE($6, sort_order),
           updated_at = NOW()
       WHERE id = $7
       RETURNING *`,
      [name, description, is_active, trigger_source, trigger_conditions ? JSON.stringify(trigger_conditions) : null, sort_order, id]
    );

    if (result.rows.length === 0) {
      return NextResponse.json({ error: 'Pipeline not found' }, { status: 404 });
    }

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

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const result = await postgresClient.query(
      `DELETE FROM webhook_pipelines WHERE id = $1 RETURNING id`, [id]
    );

    if (result.rows.length === 0) {
      return NextResponse.json({ error: 'Pipeline not found' }, { status: 404 });
    }

    return NextResponse.json({ deleted: true, id: Number(id) });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
