/**
 * Pipeline Test API — dry-run a pipeline with a sample payload.
 */

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

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

    if (!payload || typeof payload !== 'object') {
      return NextResponse.json({ error: 'payload object is required' }, { status: 400 });
    }

    // Load pipeline with steps
    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 pipeline = pipelineResult.rows[0];
    const stepsResult = await postgresClient.query(
      `SELECT * FROM pipeline_steps WHERE pipeline_id = $1 AND is_active = true ORDER BY step_order`, [id]
    );

    const pipelineWithSteps = { ...pipeline, steps: stepsResult.rows };

    // Check trigger conditions
    const conditions = Array.isArray(pipeline.trigger_conditions) ? pipeline.trigger_conditions : [];
    const conditionsMatch = pipelineEngine.evaluateConditions(conditions, payload);

    if (!conditionsMatch) {
      return NextResponse.json({
        matched: false,
        message: 'Trigger conditions did not match the provided payload',
        conditions,
      });
    }

    // Execute the pipeline
    const executionId = await pipelineEngine.executePipeline(pipelineWithSteps, pipeline.trigger_source, payload);

    // Load execution results
    const execResult = await postgresClient.query(
      `SELECT * FROM pipeline_executions WHERE id = $1`, [executionId]
    );
    const stepsLog = await postgresClient.query(
      `SELECT * FROM pipeline_execution_steps WHERE execution_id = $1 ORDER BY step_order`, [executionId]
    );

    return NextResponse.json({
      matched: true,
      execution: execResult.rows[0],
      steps: stepsLog.rows,
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
