import { InjectRepository } from '@nestjs/typeorm';
import { Province } from './entities/province.entity';
import { ILike, Not, Repository } from 'typeorm';

export class ProvincesRepository {
  constructor(
    @InjectRepository(Province)
    private readonly provinceRepository: Repository<Province>,
  ) {}

  async findAllProvince(take: number, skip: number, headers: any) {
    const [data, count] = await this.provinceRepository.findAndCount({
      where:
        headers && headers['device-type'] === 'mobile' ? { status: 1 } : {},
      skip,
      take,
      select: ['id', 'name', 'status'],
      order: { created_at: 'DESC' },
    });
    const response = {
      count,
      data,
    };

    return response;
  }

  async findById(id: string) {
    const data = await this.provinceRepository.findOne({
      where: {
        id: id,
      },
      select: ['id', 'name', 'status'],
    });
    return data;
  }

  async isUnique(name: string, id?: string) {
    const whereCondition: any = { name: ILike(name) };
    if (id) {
      whereCondition.id = Not(id);
    }

    const data = await this.provinceRepository.find({
      where: whereCondition,
    });

    return data.length > 0;
  }
}
