import { cache } from 'react';
import { db, platformSettings } from '@server/db/drizzle';
import { inArray } from 'drizzle-orm';

export interface ServerBranding {
  siteTitle: string;
  siteTagline: string;
  supportEmail: string;
  marketingUrl: string;
  logoUrl: string;
  faviconUrl: string;
}

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

const DEFAULT_BRANDING: ServerBranding = {
  siteTitle: 'RestroAgent',
  siteTagline: '',
  supportEmail: 'support@example.com',
  marketingUrl: '',
  logoUrl: '',
  faviconUrl: '',
};

function coerceString(value: unknown): string {
  if (typeof value === 'string') return value;
  if (value && typeof value === 'object' && !Array.isArray(value)) {
    const first = Object.values(value as Record<string, unknown>)[0];
    if (typeof first === 'string') return first;
  }
  return '';
}

export const getServerBranding = cache(async (): Promise<ServerBranding> => {
  try {
    const rows = await db
      .select({ key: platformSettings.key, value: platformSettings.value })
      .from(platformSettings)
      .where(inArray(platformSettings.key, BRANDING_KEYS));

    const map: Record<string, string> = {};
    for (const row of rows) {
      const v = coerceString(row.value);
      if (v) map[row.key] = v;
    }

    return {
      siteTitle: map.site_title || DEFAULT_BRANDING.siteTitle,
      siteTagline: map.site_tagline || DEFAULT_BRANDING.siteTagline,
      supportEmail: map.site_support_email || DEFAULT_BRANDING.supportEmail,
      marketingUrl: map.site_marketing_url || DEFAULT_BRANDING.marketingUrl,
      logoUrl: map.site_logo_url || DEFAULT_BRANDING.logoUrl,
      faviconUrl: map.site_favicon_url || DEFAULT_BRANDING.faviconUrl,
    };
  } catch {
    return { ...DEFAULT_BRANDING };
  }
});
