import { Injectable } from '@nestjs/common';
import { CatalogEntityKind } from '@prisma/client';
import { PrismaService } from '../../../prisma/prisma.service';

const SUPPORTED_LOCALES = ['en', 'fa', 'nl'] as const;
export type CatalogLocale = (typeof SUPPORTED_LOCALES)[number];

export function normalizeCatalogLocale(language?: string | null): CatalogLocale {
  if (language === 'fa' || language === 'nl') return language;
  return 'en';
}

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

  async resolveLabels(
    entityKind: CatalogEntityKind,
    codes: string[],
    locale: CatalogLocale,
  ): Promise<Map<string, string>> {
    const uniqueCodes = [...new Set(codes.filter(Boolean))];
    if (uniqueCodes.length === 0) {
      return new Map();
    }

    const rows = await this.prisma.catalogTranslation.findMany({
      where: {
        entityKind,
        entityCode: { in: uniqueCodes },
        locale: { in: [locale, 'en'] },
      },
      select: { entityCode: true, locale: true, label: true },
    });

    const byCode = new Map<string, { en?: string; locale?: string }>();
    for (const row of rows) {
      const entry = byCode.get(row.entityCode) ?? {};
      if (row.locale === 'en') entry.en = row.label;
      if (row.locale === locale) entry.locale = row.label;
      byCode.set(row.entityCode, entry);
    }

    const result = new Map<string, string>();
    for (const code of uniqueCodes) {
      const entry = byCode.get(code);
      result.set(code, entry?.locale ?? entry?.en ?? formatCodeAsLabel(code));
    }
    return result;
  }

  async resolveLabel(
    entityKind: CatalogEntityKind,
    code: string,
    locale: CatalogLocale,
  ): Promise<string> {
    const map = await this.resolveLabels(entityKind, [code], locale);
    return map.get(code) ?? formatCodeAsLabel(code);
  }
}

export function formatCodeAsLabel(code: string): string {
  return code
    .split('_')
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(' ');
}
