import { ConflictException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { ILike } from 'typeorm';
import { generateCode } from '../../../common/utils/generate-code.util';
import { CreateCargoTypeDto } from '../dto/create-cargo-type.dto';
import { ReorderItemsDto } from '../dto/reorder-items.dto';
import { UpdateCargoTypeDto } from '../dto/update-cargo-type.dto';
import { CargoType } from '../entities/cargo-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 with pagination and optional filtering. */
  async findAll(filter: {
    isActive?: boolean;
    requiresDirectorApproval?: boolean;
    parentGroupId?: string;
    search?: string;
    page?: number;
    pageSize?: number;
    sortBy?: string;
    sortOrder?: 'ASC' | 'DESC';
  }): Promise<{ data: CargoType[]; 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;
    if (filter.requiresDirectorApproval !== undefined) where.requiresDirectorApproval = filter.requiresDirectorApproval;
    if (filter.parentGroupId !== undefined) where.parentGroupId = filter.parentGroupId;
    if (filter.search) where.cargoTypeName = ILike(`%${filter.search}%`);

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

  /** 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,
      showFreeTextBox: dto.showFreeTextBox ?? false,
      requiresDirectorApproval: dto.requiresDirectorApproval ?? false,
      isActive: dto.isActive ?? true,
      unitOfMeasure: dto.unitOfMeasure ?? null,
      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 updated = await this.repository.update(id, dto);
    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);
  }
}
