import { NextRequest, NextResponse } from "next/server";
import { Pool } from "pg";
import { requireAdmin, requireSuperAdmin, getSession } from "@/lib/auth-utils";
import { audit } from "@/lib/services/audit";

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

// GET /api/admin/settings - Get all app settings
export async function GET(request: NextRequest) {
  const { error } = await requireAdmin();
  if (error) return error;

  try {
    const result = await pool.query(
      `SELECT key, value, description FROM "app_settings" ORDER BY key`
    );

    // Convert to key-value object
    const settings: Record<string, string> = {};
    result.rows.forEach((row) => {
      settings[row.key] = row.value;
    });

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

// PATCH /api/admin/settings - Update app settings
export async function PATCH(request: NextRequest) {
  const { session, error } = await requireSuperAdmin();
  if (error) return error;

  try {
    const body = await request.json();
    const { settings } = body;

    if (!settings || typeof settings !== "object") {
      return NextResponse.json(
        { error: "Settings object is required" },
        { status: 400 }
      );
    }

    // Update each setting
    for (const [key, value] of Object.entries(settings)) {
      // Get old value for audit
      const oldResult = await pool.query(
        'SELECT value FROM "app_settings" WHERE key = $1',
        [key]
      );
      const oldValue = oldResult.rows[0]?.value;

      await pool.query(
        `INSERT INTO "app_settings" (id, key, value, updated_at)
         VALUES ($1, $2, $3, NOW())
         ON CONFLICT (key) DO UPDATE SET value = $3, updated_at = NOW()`,
        [`setting_${key}`, key, value]
      );

      // Audit log
      if (session?.user) {
        await audit.settingsUpdated(
          session.user.id,
          session.user.email,
          key,
          oldValue,
          value
        );
      }
    }

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