/**
 * Locale resolution helper for Discord interactions.
 *
 * Reads locale preference from DB (user → guild → Discord) and returns the resolved locale.
 * This bridges Discord interactions with the i18n system.
 */

import { Interaction } from 'discord.js';
import { resolveLocale, SupportedLocale } from '../i18n';
import { prisma } from '../database';

/**
 * Resolve the best locale for a given interaction.
 *
 * Priority:
 *   1. User DB setting (UserLocale)
 *   2. Guild DB setting (GuildConfig.locale)
 *   3. Discord interaction.locale (auto-detect)
 *   4. Default: 'en'
 */
export async function getInteractionLocale(interaction: Interaction): Promise<SupportedLocale> {
  let userLocale: string | null = null;
  let guildLocale: string | null = null;

  try {
    const [userPref, guildConfig] = await Promise.all([
      prisma.userLocale.findUnique({
        where: { userId: interaction.user.id },
        select: { locale: true },
      }),
      interaction.guildId
        ? prisma.guildConfig.findUnique({
            where: { guildId: interaction.guildId },
            select: { locale: true },
          })
        : Promise.resolve(null),
    ]);
    userLocale = userPref?.locale ?? null;
    guildLocale = guildConfig?.locale ?? null;
  } catch {
    // If DB lookup fails, fall through to Discord locale / default
  }

  return resolveLocale({
    userLocale,
    guildLocale,
    discordLocale: interaction.locale,
  });
}

/**
 * Resolve locale for non-interaction contexts (e.g. VoiceService events).
 * Uses guild + user IDs directly.
 */
export async function getContextLocale(
  guildId?: string | null,
  userId?: string | null,
): Promise<SupportedLocale> {
  let userLocale: string | null = null;
  let guildLocale: string | null = null;

  try {
    const [userPref, guildConfig] = await Promise.all([
      userId
        ? prisma.userLocale.findUnique({
            where: { userId },
            select: { locale: true },
          })
        : Promise.resolve(null),
      guildId
        ? prisma.guildConfig.findUnique({
            where: { guildId },
            select: { locale: true },
          })
        : Promise.resolve(null),
    ]);
    userLocale = userPref?.locale ?? null;
    guildLocale = guildConfig?.locale ?? null;
  } catch {
    // Fall through to default
  }

  return resolveLocale({ userLocale, guildLocale });
}
