const { EmbedBuilder } = require('discord.js');

const EMBED_COLORS = {
  federated: 0x4A90E2,
  standalone: 0x6B7280,
  success: 0x22C55E,
  error: 0xEF4444,
  warning: 0xF59E0B,
};

const modeConfigCache = new Map();
const MODE_CACHE_TTL = 60000;

async function getServerMode(supabase, guildId) {
  if (!supabase) return 'standalone';
  
  const now = Date.now();
  const cached = modeConfigCache.get(guildId);
  
  if (cached && (now - cached.timestamp < MODE_CACHE_TTL)) {
    return cached.mode;
  }

  try {
    const { data } = await supabase
      .from('server_config')
      .select('mode')
      .eq('guild_id', guildId)
      .maybeSingle();

    const mode = data?.mode || 'federated';
    modeConfigCache.set(guildId, { mode, timestamp: now });
    return mode;
  } catch (e) {
    return 'federated';
  }
}

async function setServerMode(supabase, guildId, mode) {
  if (!supabase) return false;

  try {
    await supabase.from('server_config').upsert({
      guild_id: guildId,
      mode: mode,
      mode_changed_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    }, { onConflict: 'guild_id' });

    modeConfigCache.set(guildId, { mode, timestamp: Date.now() });
    return true;
  } catch (e) {
    console.error('Failed to set server mode:', e.message);
    return false;
  }
}

function clearModeCache(guildId) {
  if (guildId) {
    modeConfigCache.delete(guildId);
  } else {
    modeConfigCache.clear();
  }
}

function getEmbedColor(mode) {
  return mode === 'standalone' ? EMBED_COLORS.standalone : EMBED_COLORS.federated;
}

function createModeEmbed(mode, title, description) {
  return new EmbedBuilder()
    .setColor(getEmbedColor(mode))
    .setTitle(title)
    .setDescription(description)
    .setTimestamp();
}

function isFederated(mode) {
  return mode === 'federated';
}

function isStandalone(mode) {
  return mode === 'standalone';
}

function getModeDisplayName(mode) {
  return mode === 'federated' ? 'Federation' : 'Standalone';
}

function getModeEmoji(mode) {
  return mode === 'federated' ? '🌐' : '🏠';
}

module.exports = {
  EMBED_COLORS,
  getServerMode,
  setServerMode,
  clearModeCache,
  getEmbedColor,
  createModeEmbed,
  isFederated,
  isStandalone,
  getModeDisplayName,
  getModeEmoji,
};
