import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { getActiveTheme } from '@/lib/platform-client';
import { getRequestProductId } from '@/lib/product-config';
import tokensJson from '@bytelyst/design-tokens/tokens.json';

export async function GET(req: NextRequest) {
  try {
    const theme = await getActiveTheme(getRequestProductId(req));
    return NextResponse.json(theme);
  } catch (error) {
    logError('Failed to get active theme', error);
    // Return default theme on error to prevent app breakage

    const defaultThemeColors = {
      primary: tokensJson.color.semantic.dark.success,
      secondary: tokensJson.color.palette.neutral['700'],
      accent: tokensJson.color.semantic.dark.accentPrimary,
      background: tokensJson.color.palette.neutral['0'],
      surface: tokensJson.color.palette.neutral['50'],
      error: tokensJson.color.semantic.dark.danger,
      warning: tokensJson.color.semantic.dark.warning,
      success: tokensJson.color.semantic.dark.success,
    };

    const defaultDesktopExtras = {
      idle: tokensJson.color.semantic.dark.success,
      listening:
        (tokensJson.color as unknown as Record<string, Record<string, string>>).lysnrai
          ?.hotkeyActive ?? '#5A8CFF',
      processing: tokensJson.color.semantic.dark.warning,
      offline: tokensJson.color.semantic.dark.textSecondary,
    };

    return NextResponse.json({
      id: 'default',
      name: 'Default Green',
      description: 'Default green theme',
      ios: defaultThemeColors,
      android: defaultThemeColors,
      desktop: {
        ...defaultThemeColors,
        ...defaultDesktopExtras,
      },
      is_active: true,
      is_default: true,
      version: '1.0',
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
      created_by: null,
    });
  }
}
