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,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const result = await postgresClient.query(
      `SELECT * FROM classification_rules WHERE id = $1`,
      [id]
    );

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

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

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

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

    const fieldMap: Record<string, (v: any) => any> = {
      name: v => v,
      description: v => v,
      rule_type: v => v,
      sort_order: v => v,
      is_active: v => v,
      match_field: v => v,
      match_operator: v => v,
      match_value: v => JSON.stringify(v),
      match_case_sensitive: v => v,
      result_field: v => v,
      result_value: v => JSON.stringify(v),
      result_field_2: v => v,
      result_value_2: v => v != null ? JSON.stringify(v) : null,
      confidence: v => v,
      stop_on_match: v => v,
    };

    for (const [key, transform] of Object.entries(fieldMap)) {
      if (key in body) {
        fields.push(`${key} = $${paramIndex}`);
        values.push(transform((body as any)[key]));
        paramIndex++;
      }
    }

    if (fields.length === 0) {
      return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
    }

    fields.push(`updated_at = NOW()`);
    values.push(id);

    const result = await postgresClient.query(
      `UPDATE classification_rules SET ${fields.join(', ')} WHERE id = $${paramIndex} RETURNING *`,
      values
    );

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

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

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const result = await postgresClient.query(
      `DELETE FROM classification_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 classification rule:', error);
    return NextResponse.json({ error: 'Failed to delete classification rule' }, { status: 500 });
  }
}
