import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../../shared/prisma/prisma.service';
import { resolveTranslationFallback } from '@thebet365/shared';

@Injectable()
export class I18nService {
  constructor(private prisma: PrismaService) {}

  async getMessages(locale: string) {
    const messages = await this.prisma.i18nMessage.findMany({
      where: { locale: { in: [locale, 'en-US', 'zh-CN', 'ms-MY'] } },
    });

    const byKey: Record<string, Record<string, string>> = {};
    for (const m of messages) {
      if (!byKey[m.msgKey]) byKey[m.msgKey] = {};
      byKey[m.msgKey][m.locale] = m.value;
    }

    const result: Record<string, string> = {};
    for (const [key, locales] of Object.entries(byKey)) {
      const resolved = resolveTranslationFallback(locales, locale);
      result[key] = resolved || key;
    }
    return result;
  }

  async upsertMessage(msgKey: string, locale: string, value: string) {
    return this.prisma.i18nMessage.upsert({
      where: { msgKey_locale: { msgKey, locale } },
      create: { msgKey, locale, value },
      update: { value },
    });
  }

  async listMissing() {
    const keys = await this.prisma.i18nMessage.groupBy({ by: ['msgKey'] });
    const locales = ['zh-CN', 'ms-MY', 'en-US'];
    const missing = [];

    for (const { msgKey } of keys) {
      for (const locale of locales) {
        const exists = await this.prisma.i18nMessage.findUnique({
          where: { msgKey_locale: { msgKey, locale } },
        });
        if (!exists) missing.push({ msgKey, locale });
      }
    }
    return missing;
  }
}
