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 { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateContainerTypeDto } from '../dto/update-container-type.dto';
import { ContainerType } from '../entities/container-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 with pagination. */
  async findAll(filter: {
    isActive?: boolean;
    page?: number;
    pageSize?: number;
  }): Promise<{ data: ContainerType[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
    const page = filter.page ?? 1;
    const pageSize = filter.pageSize ?? 10;
    const where: Record<string, unknown> = {};
    if (filter.isActive !== undefined) where.isActive = filter.isActive;

    const [data, total] = await this.repository.findAndCount({
      where,
      order: { displayOrder: 'ASC' },
      skip: (page - 1) * pageSize,
      take: pageSize,
    });
    return { data, meta: { total, page, pageSize, totalPages: Math.ceil(total / pageSize) } };
  }

  /** 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,
      wagonsPerUnit: dto.wagonsPerUnit,
      isReefer: dto.isReefer ?? false,
      isOpenTop: dto.isOpenTop ?? false,
      isActive: dto.isActive ?? true,
      displayOrder,
    });
  }

  /** Update an existing container type. */
  async update(id: string, dto: UpdateContainerTypeDto): Promise<ContainerType> {
    await this.findById(id);
    const updated = await this.repository.update(id, dto);
    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);
  }
}
