import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

const defaultSettings = [
  { key: 'appName', value: 'Needyfy', category: 'branding' },
  { key: 'appTagline', value: 'Your Super App for Bangladesh', category: 'branding' },
  { key: 'appLogo', value: '🏠', category: 'branding' },
  { key: 'appMotto', value: 'Simplifying Life, One Tap at a Time', category: 'branding' },
  { key: 'primaryColor', value: '#f97316', category: 'colors' },
  { key: 'primaryHover', value: '#ea580c', category: 'colors' },
  { key: 'accentColor', value: '#f59e0b', category: 'colors' },
  { key: 'gradientFrom', value: '#ea580c', category: 'colors' },
  { key: 'gradientTo', value: '#f59e0b', category: 'colors' },
  { key: 'currencySymbol', value: '৳', category: 'general' },
  { key: 'footerText', value: '© 2025 Needyfy. All rights reserved.', category: 'general' },
  { key: 'contactPhone', value: '+880 1234-567890', category: 'general' },
  { key: 'contactEmail', value: 'support@needyfy.com', category: 'general' },
  { key: 'contactAddress', value: 'Dhaka, Bangladesh', category: 'general' },
  { key: 'enableHouseRental', value: 'true', category: 'modules' },
  { key: 'enableShopRental', value: 'true', category: 'modules' },
  { key: 'enableMarketplace', value: 'true', category: 'modules' },
  { key: 'enableMedicine', value: 'true', category: 'modules' },
  { key: 'enableEducation', value: 'true', category: 'modules' },
  { key: 'enableCommunity', value: 'true', category: 'modules' },
  { key: 'enableMessaging', value: 'true', category: 'modules' },
  { key: 'enableSeller', value: 'true', category: 'modules' },
  { key: 'darkMode', value: 'false', category: 'appearance' },
  { key: 'layoutStyle', value: 'modern', category: 'appearance' },
  { key: 'borderRadius', value: '12', category: 'appearance' },
  { key: 'fontFamily', value: 'Inter', category: 'appearance' },
];

async function seedDefaultSettings() {
  const existingCount = await db.appSetting.count();
  if (existingCount === 0) {
    await db.appSetting.createMany({ data: defaultSettings });
  }
}

export async function GET(req: NextRequest) {
  try {
    await seedDefaultSettings();

    const { searchParams } = new URL(req.url);
    const category = searchParams.get('category');

    const where = category ? { category } : {};
    const settings = await db.appSetting.findMany({
      where,
      orderBy: [{ category: 'asc' }, { key: 'asc' }],
    });

    // Group by category for convenience
    const grouped = settings.reduce(
      (acc, setting) => {
        if (!acc[setting.category]) {
          acc[setting.category] = {};
        }
        acc[setting.category][setting.key] = setting.value;
        return acc;
      },
      {} as Record<string, Record<string, string>>
    );

    // Also return flat key-value map
    const flat = settings.reduce(
      (acc, setting) => {
        acc[setting.key] = setting.value;
        return acc;
      },
      {} as Record<string, string>
    );

    return NextResponse.json({
      success: true,
      settings,
      grouped,
      flat,
    });
  } catch (error) {
    console.error('Fetch settings error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch settings' },
      { status: 500 }
    );
  }
}

export async function PATCH(req: NextRequest) {
  try {
    const { key, value, category } = await req.json();

    if (!key) {
      return NextResponse.json(
        { success: false, error: 'Key is required' },
        { status: 400 }
      );
    }

    const result = await db.appSetting.upsert({
      where: { key },
      update: { value: String(value), ...(category ? { category } : {}) },
      create: { key, value: String(value), category: category || 'general' },
    });

    return NextResponse.json({ success: true, setting: result });
  } catch (error) {
    console.error('Patch setting error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to update setting' },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    const { settings } = await req.json();

    if (!settings || !Array.isArray(settings) || settings.length === 0) {
      return NextResponse.json(
        { success: false, error: 'Settings array is required' },
        { status: 400 }
      );
    }

    const results = [];

    for (const setting of settings) {
      const { key, value, category } = setting;

      if (!key || value === undefined) {
        return NextResponse.json(
          { success: false, error: 'Each setting must have a key and value' },
          { status: 400 }
        );
      }

      const result = await db.appSetting.upsert({
        where: { key },
        update: {
          value: String(value),
          ...(category ? { category } : {}),
        },
        create: {
          key,
          value: String(value),
          category: category || 'general',
        },
      });

      results.push(result);
    }

    return NextResponse.json({ success: true, settings: results });
  } catch (error) {
    console.error('Save settings error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to save settings' },
      { status: 500 }
    );
  }
}
