import { PaginatedResponse } from '@edr/types';
import { Injectable } from '@nestjs/common';
import { DataSource, FindManyOptions, Repository } from 'typeorm';
import { paginateQuery } from '../../../common/utils/pagination.util';
import { ListContainerTypesQueryDto } from '../dto/list-rule-engine-query.dto';
import { ContainerType } from '../entities/container-type.entity';
import { IContainerTypesRepository } from '../interfaces/container-types.repository.interface';

@Injectable()
export class ContainerTypesRepository implements IContainerTypesRepository {
  private readonly repo: Repository<ContainerType>;

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

  findById(id: string): Promise<ContainerType | null> {
    return this.repo.findOne({ where: { id }, relations: { wagonTypes: true } });
  }

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

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

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

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

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

    return paginateQuery(qb, query);
  }

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

  async update(id: string, data: Partial<ContainerType>): Promise<ContainerType | null> {
    // Relation lists can't ride a column UPDATE — sync them via entity save.
    const { wagonTypes, ...columns } = data;
    if (Object.keys(columns).length) {
      await this.repo.update(id, columns as never);
    }
    if (wagonTypes) {
      const entity = await this.repo.findOne({ where: { id } });
      if (entity) {
        entity.wagonTypes = wagonTypes;
        await this.repo.save(entity);
      }
    }
    return this.findById(id);
  }

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