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

export async function GET() {
  try {
    const result = await postgresClient.query(
      `SELECT key, value, description FROM workflow_settings ORDER BY key`
    );

    const settings: Record<string, any> = {};
    for (const row of result.rows) {
      try {
        settings[row.key] = { value: JSON.parse(row.value), description: row.description };
      } catch {
        settings[row.key] = { value: row.value, description: row.description };
      }
    }

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

export async function PUT(request: NextRequest) {
  try {
    const body: Record<string, any> = await request.json();

    for (const [key, value] of Object.entries(body)) {
      await postgresClient.query(
        `UPDATE workflow_settings SET value = $1, updated_at = NOW() WHERE key = $2`,
        [JSON.stringify(value), key]
      );
    }

    // Return updated settings
    const result = await postgresClient.query(
      `SELECT key, value, description FROM workflow_settings ORDER BY key`
    );

    const settings: Record<string, any> = {};
    for (const row of result.rows) {
      try {
        settings[row.key] = { value: JSON.parse(row.value), description: row.description };
      } catch {
        settings[row.key] = { value: row.value, description: row.description };
      }
    }

    return NextResponse.json(settings);
  } catch (error) {
    console.error('Failed to update settings:', error);
    return NextResponse.json({ error: 'Failed to update settings' }, { status: 500 });
  }
}
