import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, ILike } from 'typeorm';
import { ClsService } from 'nestjs-cls';
import { TagEntity } from '../../entities/tag.entity';
import { CLS_TENANT_ID } from '../../common/cls/cls.constants';

@Injectable()
export class TagService {
  constructor(
    @InjectRepository(TagEntity)
    private readonly repo: Repository<TagEntity>,
    private readonly cls: ClsService,
  ) {}

  private getTenantId(): string {
    return this.cls.get<string>(CLS_TENANT_ID);
  }

  async findAll(search?: string, type?: string): Promise<TagEntity[]> {
    const tenantId = this.getTenantId();
    const where: any = { tenant_id: tenantId, is_deleted: false };
    if (search) where.name = ILike(`%${search}%`);
    if (type) where.type = type;
    return this.repo.find({ where, order: { name: 'ASC' }, take: 50 });
  }

  async findOrCreate(name: string, type: string = 'remark'): Promise<TagEntity> {
    const tenantId = this.getTenantId();
    const trimmed = name.trim();
    const existing = await this.repo.findOne({
      where: { tenant_id: tenantId, name: trimmed, type, is_deleted: false } as any,
    });
    if (existing) return existing;

    const tag = this.repo.create({
      tenant_id: tenantId,
      name: trimmed,
      type,
    } as any);
    return this.repo.save(tag) as unknown as Promise<TagEntity>;
  }
}
