import { NextRequest, NextResponse } from 'next/server';
import { db, platformSettings } from '@server/db/drizzle';
import { inArray } from 'drizzle-orm';
import { wrapRouteHandler } from '@server/logger/request';

const BRANDING_KEYS = ['site_logo_url', 'site_favicon_url', 'site_primary_color', 'site_font_family', 'site_title', 'site_tagline', 'site_support_email', 'site_marketing_url'];

async function handleGET(_req: NextRequest) {
  try {
    const rows = await db.select({
      key: platformSettings.key,
      value: platformSettings.value,
    })
    .from(platformSettings)
    .where(inArray(platformSettings.key, BRANDING_KEYS));

    const branding: Record<string, string> = {};
    for (const row of rows) {
      const v = row.value;
      if (typeof v === 'string') {
        branding[row.key] = v;
      } else if (typeof v === 'object' && v !== null && !Array.isArray(v)) {
        const first = Object.values(v)[0];
        branding[row.key] = typeof first === 'string' ? first : '';
      } else {
        branding[row.key] = '';
      }
    }
    return NextResponse.json({ branding }, {
      headers: { 'Cache-Control': 'no-store' },
    });
  } catch {
    return NextResponse.json({ branding: {} });
  }
}

export const GET = wrapRouteHandler((req: Request) => handleGET(req as NextRequest));
