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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const ruleResult = await postgresClient.query(
      `SELECT * FROM workflow_rules WHERE id = $1`, [id]
    );

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

    const rule = ruleResult.rows[0];
    const [conditions, actions] = await Promise.all([
      postgresClient.query(`SELECT * FROM workflow_conditions WHERE rule_id = $1 ORDER BY condition_group, id`, [id]),
      postgresClient.query(`SELECT * FROM workflow_actions WHERE rule_id = $1 ORDER BY sort_order`, [id]),
    ]);

    return NextResponse.json({ ...rule, conditions: conditions.rows, actions: actions.rows });
  } catch (error) {
    console.error('Failed to fetch workflow rule:', error);
    return NextResponse.json({ error: 'Failed to fetch workflow rule' }, { status: 500 });
  }
}

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

    // Update rule fields
    const fields: string[] = [];
    const values: any[] = [];
    let paramIndex = 1;

    for (const key of ['name', 'description', 'is_active', 'sort_order', 'trigger_event', 'trigger_entity', 'stop_processing']) {
      if (key in body) {
        fields.push(`${key} = $${paramIndex}`);
        values.push((body as any)[key]);
        paramIndex++;
      }
    }

    if (fields.length > 0) {
      fields.push(`updated_at = NOW()`);
      values.push(id);
      await postgresClient.query(
        `UPDATE workflow_rules SET ${fields.join(', ')} WHERE id = $${paramIndex}`,
        values
      );
    }

    // Replace conditions if provided
    if (body.conditions) {
      await postgresClient.query(`DELETE FROM workflow_conditions WHERE rule_id = $1`, [id]);
      for (const cond of body.conditions) {
        await postgresClient.query(
          `INSERT INTO workflow_conditions (rule_id, condition_group, field, operator, value)
           VALUES ($1, $2, $3, $4, $5)`,
          [id, cond.condition_group ?? 0, cond.field, cond.operator, JSON.stringify(cond.value)]
        );
      }
    }

    // Replace actions if provided
    if (body.actions) {
      await postgresClient.query(`DELETE FROM workflow_actions WHERE rule_id = $1`, [id]);
      for (const action of body.actions) {
        await postgresClient.query(
          `INSERT INTO workflow_actions (rule_id, sort_order, action_type, config)
           VALUES ($1, $2, $3, $4)`,
          [id, action.sort_order ?? 0, action.action_type, JSON.stringify(action.config ?? {})]
        );
      }
    }

    // Return updated rule
    const ruleResult = await postgresClient.query(`SELECT * FROM workflow_rules WHERE id = $1`, [id]);
    if (ruleResult.rows.length === 0) {
      return NextResponse.json({ error: 'Not found' }, { status: 404 });
    }

    const [conditions, actions] = await Promise.all([
      postgresClient.query(`SELECT * FROM workflow_conditions WHERE rule_id = $1`, [id]),
      postgresClient.query(`SELECT * FROM workflow_actions WHERE rule_id = $1 ORDER BY sort_order`, [id]),
    ]);

    return NextResponse.json({ ...ruleResult.rows[0], conditions: conditions.rows, actions: actions.rows });
  } catch (error) {
    console.error('Failed to update workflow rule:', error);
    return NextResponse.json({ error: 'Failed to update workflow rule' }, { status: 500 });
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    // CASCADE will delete conditions and actions
    const result = await postgresClient.query(
      `DELETE FROM workflow_rules WHERE id = $1 RETURNING id`, [id]
    );

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

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Failed to delete workflow rule:', error);
    return NextResponse.json({ error: 'Failed to delete workflow rule' }, { status: 500 });
  }
}
