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

export async function GET(request: NextRequest) {
  try {
    const result = await postgresClient.query(
      'SELECT setting_key, setting_value, description FROM kiosk_settings'
    );

    const settings: Record<string, any> = {};
    result.rows.forEach((row: any) => {
      let value = row.setting_value;
      
      // Parse specific settings
      if (row.setting_key === 'excluded_company_ids' || row.setting_key === 'excluded_classifications') {
        value = value ? value.split(',').map((item: string) => item.trim()).filter(Boolean) : [];
      } else if (row.setting_key === 'show_rmm_alerts') {
        value = value === 'true';
      } else if (['cycle_interval', 'refresh_interval', 'ticker_speed'].includes(row.setting_key)) {
        value = parseInt(value || '0');
      }
      
      settings[row.setting_key] = value;
    });

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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { setting_key, setting_value } = body;

    if (!setting_key) {
      return NextResponse.json(
        { error: 'setting_key is required' },
        { status: 400 }
      );
    }

    // Convert arrays and booleans to strings for storage
    let valueToStore = setting_value;
    if (Array.isArray(setting_value)) {
      valueToStore = setting_value.join(',');
    } else if (typeof setting_value === 'boolean') {
      valueToStore = setting_value.toString();
    } else if (typeof setting_value === 'number') {
      valueToStore = setting_value.toString();
    }

    await postgresClient.query(
      `INSERT INTO kiosk_settings (setting_key, setting_value, updated_at)
       VALUES ($1, $2, CURRENT_TIMESTAMP)
       ON CONFLICT (setting_key) 
       DO UPDATE SET setting_value = EXCLUDED.setting_value, updated_at = CURRENT_TIMESTAMP`,
      [setting_key, valueToStore]
    );

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