import { PaginatedResponse } from '@edr/types';
import { ConflictException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { generateCode } from '../../../common/utils/generate-code.util';
import { CreateCargoTypeDto } from '../dto/create-cargo-type.dto';
import { ListCargoTypesQueryDto } from '../dto/list-rule-engine-query.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateCargoTypeDto } from '../dto/update-cargo-type.dto';
import { CargoType } from '../entities/cargo-type.entity';
import { WagonType } from '../../wagon-types/entities/wagon-type.entity';
import {
  CARGO_TYPES_REPOSITORY,
  ICargoTypesRepository,
} from '../interfaces/cargo-types.repository.interface';
import { DisplayOrderService } from './display-order.service';

@Injectable()
export class CargoTypesService {
  constructor(
    @Inject(CARGO_TYPES_REPOSITORY)
    private readonly repository: ICargoTypesRepository,
    private readonly displayOrder: DisplayOrderService,
  ) {}

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

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

  /** Get a cargo type by code. */
  async findByCode(code: string): Promise<CargoType | null> {
    return this.repository.findByCode(code);
  }

  /** Create a new cargo type. */
  async create(dto: CreateCargoTypeDto): Promise<CargoType> {
    const code = generateCode(dto.cargoTypeName);
    const existing = await this.repository.findByCode(code);
    if (existing) throw new ConflictException(`Cargo type with name "${dto.cargoTypeName}" conflicts with existing code "${code}"`);
    if (dto.parentGroupId) {
      const parent = await this.repository.findById(dto.parentGroupId);
      if (!parent) throw new NotFoundException(`Parent cargo type ${dto.parentGroupId} not found`);
    }

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

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

  /** Update an existing cargo type. */
  async update(id: string, dto: UpdateCargoTypeDto): Promise<CargoType> {
    await this.findById(id);
    if (dto.parentGroupId) {
      if (dto.parentGroupId === id) throw new ConflictException('A cargo type cannot be its own parent');
      const parent = await this.repository.findById(dto.parentGroupId);
      if (!parent) throw new NotFoundException(`Parent cargo type ${dto.parentGroupId} not found`);
    }
    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(`Cargo type ${id} not found`);
    return updated;
  }

  /** Soft-delete a cargo 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(CargoType, 'displayOrder', dto.ids);
  }

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