import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BaseRepository } from '@edr/api-common';
import { Company } from './entities/company.entity';

@Injectable()
export class CompaniesRepository extends BaseRepository<Company> {
  constructor(
    @InjectRepository(Company)
    repo: Repository<Company>,
  ) {
    super(repo);
  }

  async findByTin(tin: string): Promise<Company | null> {
    return this.repository.findOne({ where: { tin } as any });
  }

  async findByType(type: string): Promise<Company[]> {
    return this.repository.find({ where: { type } as any, order: { name: 'ASC' } });
  }

  async findByName(name: string): Promise<Company[]> {
    return this.repository
      .createQueryBuilder('company')
      .where('company.name ILIKE :name', { name: `%${name}%` })
      .getMany();
  }

  async existsByTin(tin: string): Promise<boolean> {
    const count = await this.repository.count({ where: { tin } as any });
    return count > 0;
  }
}
