/**
 * GET /api/ticket-workflows/:id - Get workflow with steps
 * PUT /api/ticket-workflows/:id - Update workflow
 * DELETE /api/ticket-workflows/:id - Delete workflow
 */

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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    const workflowResult = await postgresClient.query<TicketWorkflow>(
      `SELECT * FROM ticket_workflows WHERE id = $1`,
      [id]
    );

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

    const stepsResult = await postgresClient.query<TicketWorkflowStep>(
      `SELECT * FROM ticket_workflow_steps WHERE workflow_id = $1 ORDER BY step_order`,
      [id]
    );

    return NextResponse.json({
      workflow: workflowResult.rows[0],
      steps: stepsResult.rows
    });
  } catch (error) {
    console.error('[API] Error fetching workflow:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to fetch workflow' },
      { 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_event, trigger_conditions, sort_order } = body;

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

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

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

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    await postgresClient.query(
      `DELETE FROM ticket_workflows WHERE id = $1`,
      [id]
    );

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('[API] Error deleting workflow:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to delete workflow' },
      { status: 500 }
    );
  }
}
