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

@Injectable()
export class PartRepository extends BaseRepository<Part> {
  constructor(
    @InjectRepository(Part)
    private readonly partRepository: Repository<Part>,
  ) {
    super(partRepository);
  }

  async findFiltered(filters: { category?: string; lowStock?: boolean }) {
    const qb = this.partRepository.createQueryBuilder('part');
    if (filters.category) {
      qb.andWhere('part.category = :category', { category: filters.category });
    }
    if (filters.lowStock) {
      qb.andWhere('part.quantityInStock <= part.reorderLevel');
    }
    qb.orderBy('part.name', 'ASC');
    return qb.getMany();
  }
}
