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: '/logo-needyfy.png', category: 'branding' },
  { key: 'appLogoUrl', value: '', category: 'branding' },
  { key: 'faviconUrl', value: '', category: 'branding' },
  { key: 'appMotto', value: 'Simplifying Life, One Tap at a Time', category: 'branding' },
  { key: 'appDescription', value: 'Bangladesh\'s complete super app for all your daily needs', 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' },
  // SEO
  { key: 'seoTitle', value: 'Needyfy - Every Need, One Platform', category: 'seo' },
  { key: 'seoDescription', value: 'Bangladesh\'s complete super app for house rental, shop rental, marketplace, medicine, MCQ exam and more.', category: 'seo' },
  { key: 'ogImage', value: '', category: 'seo' },
  // Splash & Loading
  { key: 'splashBgColor', value: '#1d4ed8', category: 'branding' },
  { key: 'splashLogoUrl', value: '', category: 'branding' },
];

// In-memory cache to avoid re-seeding on every request
let seedCompleted = false;

async function seedDefaultSettings() {
  if (seedCompleted) return;

  try {
    const existingCount = await db.appSetting.count();
    if (existingCount === 0) {
      await db.appSetting.createMany({ data: defaultSettings });
    } else {
      // Only check for missing keys - do it efficiently in one query
      const existingKeys = await db.appSetting.findMany({
        select: { key: true },
      });
      const keySet = new Set(existingKeys.map((s) => s.key));

      const missing = defaultSettings.filter((s) => !keySet.has(s.key));
      if (missing.length > 0) {
        await db.appSetting.createMany({ data: missing });
      }
    }
    seedCompleted = true;
  } catch (error) {
    console.error('Seed settings error:', error);
    // Don't mark as completed so it retries next time
  }
}

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 POST(req: NextRequest) {
  try {
    const body = await req.json();

    // Support both array format and object format
    let settings: { key: string; value: string; category?: string }[];

    if (Array.isArray(body.settings)) {
      settings = body.settings;
    } else if (Array.isArray(body)) {
      settings = body;
    } else if (body.key) {
      // Single setting update
      settings = [body];
    } else {
      // Object format: { key1: value1, key2: value2 } with optional category
      const category = body._category || 'general';
      settings = Object.entries(body)
        .filter(([k]) => !k.startsWith('_'))
        .map(([key, value]) => ({ key, value: String(value), category }));
    }

    if (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) {
        continue;
      }

      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 }
    );
  }
}

export async function PATCH(req: NextRequest) {
  try {
    const body = await req.json();
    const { action } = body;

    if (action === 'changePassword') {
      // Handle password change - this is a separate concern
      return NextResponse.json({ success: true, message: 'Password change not implemented in this route' });
    }

    // Single setting update
    const { key, value, category } = body;
    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('Update setting error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to update setting' },
      { status: 500 }
    );
  }
}
