/**
 * Pipelines API — list and create webhook pipelines.
 */

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

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const source = searchParams.get('source');

    let query = `SELECT * FROM webhook_pipelines`;
    const params: any[] = [];

    if (source) {
      query += ` WHERE trigger_source = $1`;
      params.push(source);
    }

    query += ` ORDER BY sort_order, name`;

    const result = await postgresClient.query(query, params);

    // Load step counts
    const pipelines = await Promise.all(
      result.rows.map(async (p: any) => {
        const stepsResult = await postgresClient.query(
          `SELECT COUNT(*) as count FROM pipeline_steps WHERE pipeline_id = $1`,
          [p.id]
        );
        return { ...p, step_count: parseInt(stepsResult.rows[0].count) };
      })
    );

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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { name, description, is_active, trigger_source, trigger_conditions, sort_order } = body;

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

    const result = await postgresClient.query(
      `INSERT INTO webhook_pipelines (name, description, is_active, trigger_source, trigger_conditions, sort_order)
       VALUES ($1, $2, $3, $4, $5, $6)
       RETURNING *`,
      [name, description || null, is_active ?? true, trigger_source, JSON.stringify(trigger_conditions || []), sort_order || 0]
    );

    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 });
  }
}
