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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const ruleType = searchParams.get('rule_type');

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

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

    query += ` ORDER BY rule_type, sort_order`;

    const result = await postgresClient.query(query, params);
    return NextResponse.json(result.rows);
  } catch (error) {
    console.error('Failed to fetch classification rules:', error);
    return NextResponse.json({ error: 'Failed to fetch classification rules' }, { status: 500 });
  }
}

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

    const result = await postgresClient.query(
      `INSERT INTO classification_rules
       (name, description, rule_type, sort_order, is_active, match_field, match_operator, match_value,
        match_case_sensitive, result_field, result_value, result_field_2, result_value_2, confidence, stop_on_match)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
       RETURNING *`,
      [
        body.name,
        body.description || null,
        body.rule_type,
        body.sort_order ?? 0,
        body.is_active ?? true,
        body.match_field,
        body.match_operator,
        JSON.stringify(body.match_value),
        body.match_case_sensitive ?? false,
        body.result_field,
        JSON.stringify(body.result_value),
        body.result_field_2 || null,
        body.result_value_2 ? JSON.stringify(body.result_value_2) : null,
        body.confidence ?? 'high',
        body.stop_on_match ?? true,
      ]
    );

    return NextResponse.json(result.rows[0], { status: 201 });
  } catch (error) {
    console.error('Failed to create classification rule:', error);
    return NextResponse.json({ error: 'Failed to create classification rule' }, { status: 500 });
  }
}
