/**
 * GET /api/ticket-workflows - List all ticket workflows
 * POST /api/ticket-workflows - Create a new workflow
 */

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

export async function GET(request: NextRequest) {
  try {
    const result = await postgresClient.query<TicketWorkflow>(
      `SELECT tw.*,
              (SELECT COUNT(*) FROM ticket_workflow_steps WHERE workflow_id = tw.id) as step_count,
              (SELECT COUNT(*) FROM ticket_workflow_executions WHERE workflow_id = tw.id AND created_at > NOW() - INTERVAL '24 hours') as executions_today
       FROM ticket_workflows tw
       ORDER BY sort_order, id`
    );

    return NextResponse.json({ workflows: result.rows });
  } catch (error) {
    console.error('[API] Error fetching ticket workflows:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to fetch workflows' },
      { status: 500 }
    );
  }
}

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

    if (!name || !trigger_event) {
      return NextResponse.json(
        { error: 'Missing required fields: name, trigger_event' },
        { status: 400 }
      );
    }

    const result = await postgresClient.query<TicketWorkflow>(
      `INSERT INTO ticket_workflows (name, description, trigger_event, trigger_conditions, is_active, sort_order)
       VALUES ($1, $2, $3, $4, $5, $6)
       RETURNING *`,
      [
        name,
        description || null,
        trigger_event,
        JSON.stringify(trigger_conditions || []),
        is_active !== undefined ? is_active : true,
        sort_order || 0
      ]
    );

    return NextResponse.json({ workflow: result.rows[0] }, { status: 201 });
  } catch (error) {
    console.error('[API] Error creating ticket workflow:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to create workflow' },
      { status: 500 }
    );
  }
}
