import { NextResponse } from 'next/server';
import db from '@/lib/db';
import { getServerSession } from 'next-auth/next';

export async function GET() {
  try {
    const configs = await db.query('SELECT * FROM SiteConfig');
    return NextResponse.json(configs);
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function POST(request: Request) {
  const session = await getServerSession();
  // Simplified auth check for now, should be expanded for production
  if (!session) {
    // return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const { key, value } = await request.json();
    
    // Upsert logic for SQLite/MySQL
    await db.execute(`
      INSERT INTO SiteConfig (id, config_key, config_value, updatedAt) 
      VALUES (UUID(), ?, ?, NOW())
      ON DUPLICATE KEY UPDATE config_value = VALUES(config_value), updatedAt = NOW()
    `, [key, value]);

    return NextResponse.json({ success: true });
  } catch (error: any) {
    // Fallback for SQLite which doesn't support ON DUPLICATE KEY UPDATE the same way
    try {
        const { key, value } = await request.json();
        const existing = await db.query('SELECT id FROM SiteConfig WHERE config_key = ?', [key]) as any[];
        if (existing.length > 0) {
            await db.execute('UPDATE SiteConfig SET config_value = ?, updatedAt = CURRENT_TIMESTAMP WHERE config_key = ?', [value, key]);
        } else {
            const id = Math.random().toString(36).substring(2, 15);
            await db.execute('INSERT INTO SiteConfig (id, config_key, config_value) VALUES (?, ?, ?)', [id, key, value]);
        }
        return NextResponse.json({ success: true });
    } catch (e: any) {
        return NextResponse.json({ error: e.message }, { status: 500 });
    }
  }
}
