import { PaginatedResponse } from '@edr/types';
import { Injectable } from '@nestjs/common';
import { DataSource, FindManyOptions, Repository } from 'typeorm';
import { paginateQuery } from '../../../common/utils/pagination.util';
import { ListRuleEngineQueryDto } from '../dto/list-rule-engine-query.dto';
import { ShippingLine } from '../entities/shipping-line.entity';
import { IShippingLinesRepository } from '../interfaces/shipping-lines.repository.interface';

@Injectable()
export class ShippingLinesRepository implements IShippingLinesRepository {
  private readonly repo: Repository<ShippingLine>;

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

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

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

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

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

  /** Paged list with server-side search (label/code/mappedToCode), ordered by code. */
  findPaged(query: ListRuleEngineQueryDto): Promise<PaginatedResponse<ShippingLine>> {
    const qb = this.repo
      .createQueryBuilder('line')
      .orderBy('line.code', query.sortOrder ?? 'ASC');

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

    return paginateQuery(qb, query);
  }

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

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

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