import { PaginatedResponse } from '@edr/types';
import { Injectable } from '@nestjs/common';
import { DataSource, FindManyOptions, Repository } from 'typeorm';
import { paginateQuery } from '../../../common/utils/pagination.util';
import { ListYardsQueryDto } from '../dto/list-rule-engine-query.dto';
import { Yard } from '../entities/yard.entity';
import { IYardsRepository } from '../interfaces/yards.repository.interface';

@Injectable()
export class YardsRepository implements IYardsRepository {
  private readonly repo: Repository<Yard>;

  constructor(private readonly dataSource: DataSource) {
    this.repo = this.dataSource.getRepository(Yard);
  }

  findById(id: string): Promise<Yard | null> {
    return this.repo.findOne({ where: { id } });
  }

  findByCode(code: string): Promise<Yard | null> {
    return this.repo.findOne({ where: { code } });
  }

  findAll(options?: FindManyOptions<Yard>): Promise<Yard[]> {
    return this.repo.find(options);
  }

  findAndCount(options?: FindManyOptions<Yard>): Promise<[Yard[], number]> {
    return this.repo.findAndCount(options);
  }

  /** Paged list with server-side search (label/code/country) in the standard envelope. */
  findPaged(query: ListYardsQueryDto): Promise<PaginatedResponse<Yard>> {
    const qb = this.repo
      .createQueryBuilder('yard')
      .orderBy(`yard.${query.sortBy ?? 'displayOrder'}`, query.sortOrder ?? 'ASC')
      .addOrderBy('yard.label', 'ASC');

    if (query.isActive !== undefined) {
      qb.andWhere('yard.isActive = :isActive', { isActive: query.isActive });
    }
    if (query.country) {
      qb.andWhere('yard.country = :country', { country: query.country });
    }
    if (query.search) {
      qb.andWhere(
        '(yard.label ILIKE :search OR yard.code ILIKE :search OR yard.country ILIKE :search)',
        { search: `%${query.search}%` },
      );
    }

    return paginateQuery(qb, query);
  }

  async create(data: Partial<Yard>): Promise<Yard> {
    const entity = this.repo.create(data);
    return this.repo.save(entity);
  }

  async update(id: string, data: Partial<Yard>): Promise<Yard | null> {
    await this.repo.update(id, data);
    return this.findById(id);
  }

  async softDelete(id: string): Promise<void> {
    await this.repo.softDelete(id);
  }
}
