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

export async function GET() {
  try {
    const rules = await postgresClient.query(
      `SELECT * FROM workflow_rules ORDER BY sort_order`
    );

    // Load conditions and actions for each rule
    const rulesWithDetails = await Promise.all(
      rules.rows.map(async (rule: any) => {
        const [conditions, actions] = await Promise.all([
          postgresClient.query(`SELECT * FROM workflow_conditions WHERE rule_id = $1 ORDER BY condition_group, id`, [rule.id]),
          postgresClient.query(`SELECT * FROM workflow_actions WHERE rule_id = $1 ORDER BY sort_order`, [rule.id]),
        ]);
        return { ...rule, conditions: conditions.rows, actions: actions.rows };
      })
    );

    return NextResponse.json(rulesWithDetails);
  } catch (error) {
    console.error('Failed to fetch workflow rules:', error);
    return NextResponse.json({ error: 'Failed to fetch workflow rules' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body: WorkflowRuleInput = await request.json();

    // Insert rule
    const ruleResult = await postgresClient.query(
      `INSERT INTO workflow_rules (name, description, is_active, sort_order, trigger_event, trigger_entity, stop_processing)
       VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *`,
      [
        body.name,
        body.description || null,
        body.is_active ?? true,
        body.sort_order ?? 0,
        body.trigger_event,
        body.trigger_entity ?? 'ticket',
        body.stop_processing ?? false,
      ]
    );

    const rule = ruleResult.rows[0];

    // Insert conditions
    if (body.conditions?.length) {
      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)`,
          [rule.id, cond.condition_group ?? 0, cond.field, cond.operator, JSON.stringify(cond.value)]
        );
      }
    }

    // Insert actions
    if (body.actions?.length) {
      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)`,
          [rule.id, action.sort_order ?? 0, action.action_type, JSON.stringify(action.config ?? {})]
        );
      }
    }

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

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