import { NextResponse } from 'next/server';
import { db } from '@/db/connection';
import { settings } from '@/db/schema';
import { eq } from 'drizzle-orm';
import { getAuthUser, generateId } from '@/lib/auth';

// Helper: check admin access
function checkAdmin(request: Request) {
  const user = getAuthUser(request);
  if (!user) {
    return NextResponse.json(
      { success: false, error: 'กรุณาเข้าสู่ระบบ' },
      { status: 401 }
    );
  }
  if (!user.isAdmin) {
    return NextResponse.json(
      { success: false, error: 'ไม่มีสิทธิ์เข้าถึง' },
      { status: 403 }
    );
  }
  return null;
}

// ==================== GET /api/admin/settings ====================
export async function GET(request: Request) {
  try {
    const authError = checkAdmin(request);
    if (authError) return authError;

    const allSettings = await db.select().from(settings);

    // Convert to key-value object
    const settingsObj: Record<string, string> = {};
    for (const setting of allSettings) {
      settingsObj[setting.key] = setting.value;
    }

    return NextResponse.json({
      success: true,
      settings: settingsObj,
    });
  } catch (error) {
    console.error('GET /api/admin/settings error:', error);
    return NextResponse.json(
      { success: false, error: 'เกิดข้อผิดพลาดในระบบ' },
      { status: 500 }
    );
  }
}

// ==================== PUT /api/admin/settings ====================
export async function PUT(request: Request) {
  try {
    const authError = checkAdmin(request);
    if (authError) return authError;

    const body = await request.json();
    const { settings: settingsInput } = body as {
      settings?: Record<string, string>;
    };

    if (!settingsInput || typeof settingsInput !== 'object') {
      return NextResponse.json(
        { success: false, error: 'กรุณาระบุข้อมูลการตั้งค่า' },
        { status: 400 }
      );
    }

    // Upsert each key-value pair
    for (const [key, value] of Object.entries(settingsInput)) {
      // Check if setting exists
      const existing = await db
        .select({ id: settings.id })
        .from(settings)
        .where(eq(settings.key, key))
        .limit(1);

      if (existing.length > 0) {
        // Update existing
        await db
          .update(settings)
          .set({ value, updatedAt: new Date() })
          .where(eq(settings.key, key));
      } else {
        // Create new
        await db.insert(settings).values({
          id: generateId(),
          key,
          value,
          updatedAt: new Date(),
        });
      }
    }

    // Return updated settings as key-value object
    const allSettings = await db.select().from(settings);
    const settingsObj: Record<string, string> = {};
    for (const setting of allSettings) {
      settingsObj[setting.key] = setting.value;
    }

    return NextResponse.json({
      success: true,
      settings: settingsObj,
    });
  } catch (error) {
    console.error('PUT /api/admin/settings error:', error);
    return NextResponse.json(
      { success: false, error: 'เกิดข้อผิดพลาดในระบบ' },
      { status: 500 }
    );
  }
}
