import { PaginatedResponse } from '@edr/types';
import { ConflictException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { generateCode } from '../../../common/utils/generate-code.util';
import { CreateContainerTypeDto } from '../dto/create-container-type.dto';
import { ListContainerTypesQueryDto } from '../dto/list-rule-engine-query.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateContainerTypeDto } from '../dto/update-container-type.dto';
import { ContainerType } from '../entities/container-type.entity';
import { WagonType } from '../../wagon-types/entities/wagon-type.entity';
import {
  CONTAINER_TYPES_REPOSITORY,
  IContainerTypesRepository,
} from '../interfaces/container-types.repository.interface';
import { DisplayOrderService } from './display-order.service';

@Injectable()
export class ContainerTypesService {
  constructor(
    @Inject(CONTAINER_TYPES_REPOSITORY)
    private readonly repository: IContainerTypesRepository,
    private readonly displayOrder: DisplayOrderService,
  ) {}

  /** List container types — standard paginated envelope with server-side search. */
  async findAll(query: ListContainerTypesQueryDto): Promise<PaginatedResponse<ContainerType>> {
    return this.repository.findPaged(query);
  }

  /** Get a single container type by ID. */
  async findById(id: string): Promise<ContainerType> {
    const entity = await this.repository.findById(id);
    if (!entity) throw new NotFoundException(`Container type ${id} not found`);
    return entity;
  }

  /** Create a new container type. */
  async create(dto: CreateContainerTypeDto): Promise<ContainerType> {
    const code = generateCode(dto.label);
    const existing = await this.repository.findByCode(code);
    if (existing) throw new ConflictException(`Container type with label "${dto.label}" conflicts with existing code "${code}"`);

    const displayOrder = await this.displayOrder.resolveCreateOrder(ContainerType, 'displayOrder', {
      explicitOrder: dto.displayOrder,
      insertAfterId: dto.insertAfterId,
    });

    return this.repository.create({
      code,
      label: dto.label,
      sizeFt: dto.sizeFt,
      isReefer: dto.isReefer ?? false,
      isOpenTop: dto.isOpenTop ?? false,
      isActive: dto.isActive ?? true,
      // Join rows are written by the save (RESTRICT FK rejects unknown ids).
      wagonTypes: (dto.wagonTypeIds ?? []).map((id) => ({ id }) as WagonType),
      displayOrder,
    });
  }

  /** Update an existing container type. */
  async update(id: string, dto: UpdateContainerTypeDto): Promise<ContainerType> {
    await this.findById(id);
    const { wagonTypeIds, insertAfterId: _insertAfterId, ...columns } = dto;
    const updated = await this.repository.update(id, {
      ...columns,
      ...(wagonTypeIds
        ? { wagonTypes: wagonTypeIds.map((wagonTypeId) => ({ id: wagonTypeId }) as WagonType) }
        : {}),
    });
    if (!updated) throw new NotFoundException(`Container type ${id} not found`);
    return updated;
  }

  /** Soft-delete a container type. */
  async remove(id: string): Promise<void> {
    await this.findById(id);
    await this.repository.softDelete(id);
  }

  async reorder(dto: ReorderItemsDto): Promise<void> {
    await this.displayOrder.reorderByIds(ContainerType, 'displayOrder', dto.ids);
  }

  async moveOrder(id: string, direction: 'up' | 'down'): Promise<void> {
    await this.findById(id);
    await this.displayOrder.moveOne(ContainerType, 'displayOrder', id, direction);
  }
}
