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

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

  /**
   * 按 category 拉字典项（前端下拉用）
   * 常用 category：
   *   - label_type          质量标签类型
   *   - tariff_type         关税类型
   *   - declaration_type    进口申报类型
   *   - service_issue_type  售后问题类型
   *   - industry            客户行业
   */
  listByCategory(category: string): Promise<Dictionary[]> {
    return this.prisma.dictionary.findMany({
      where: { category, enabled: true },
      orderBy: { sortOrder: 'asc' },
    });
  }

  listCategories(): Promise<string[]> {
    return this.prisma.dictionary
      .findMany({
        where: { enabled: true },
        select: { category: true },
        distinct: ['category'],
        orderBy: { category: 'asc' },
      })
      .then((rows) => rows.map((r) => r.category));
  }

  findByCode(category: string, code: string): Promise<Dictionary | null> {
    return this.prisma.dictionary.findUnique({
      where: { category_code: { category, code } },
    });
  }
}
