import { Inject, Injectable, NotFoundException } from '@nestjs/common';
import { CreateWeightLimitRuleDto } from '../dto/create-weight-limit-rule.dto';
import { UpdateWeightLimitRuleDto } from '../dto/update-weight-limit-rule.dto';
import { WeightLimitRule } from '../entities/weight-limit-rule.entity';
import {
  IWeightLimitRulesRepository,
  WEIGHT_LIMIT_RULES_REPOSITORY,
} from '../interfaces/weight-limit-rules.repository.interface';

@Injectable()
export class WeightLimitRulesService {
  constructor(
    @Inject(WEIGHT_LIMIT_RULES_REPOSITORY)
    private readonly repository: IWeightLimitRulesRepository,
  ) {}

  /** List weight limit rules with pagination. */
  async findAll(filter: {
    containerTypeId?: string;
    tradeDirection?: string;
    page?: number;
    pageSize?: number;
  }): Promise<{ data: WeightLimitRule[]; meta: { total: number; page: number; pageSize: number; totalPages: number } }> {
    const page = filter.page ?? 1;
    const pageSize = filter.pageSize ?? 20;
    const where: Record<string, unknown> = {};
    if (filter.containerTypeId) where.containerTypeId = filter.containerTypeId;
    if (filter.tradeDirection) where.tradeDirection = filter.tradeDirection;

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

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

  /** Create a new weight limit rule. */
  async create(dto: CreateWeightLimitRuleDto): Promise<WeightLimitRule> {
    return this.repository.create({
      containerTypeId: dto.containerTypeId,
      tradeDirection: dto.tradeDirection,
      maxVgmTons: dto.maxVgmTons,
      effectiveFrom: new Date(dto.effectiveFrom),
      effectiveTo: dto.effectiveTo ? new Date(dto.effectiveTo) : null,
    });
  }

  /** Update an existing weight limit rule. */
  async update(id: string, dto: UpdateWeightLimitRuleDto): Promise<WeightLimitRule> {
    await this.findById(id);
    const patch: Partial<WeightLimitRule> = {};
    if (dto.containerTypeId !== undefined) patch.containerTypeId = dto.containerTypeId;
    if (dto.tradeDirection !== undefined) patch.tradeDirection = dto.tradeDirection;
    if (dto.maxVgmTons !== undefined) patch.maxVgmTons = dto.maxVgmTons;
    if (dto.effectiveFrom !== undefined) patch.effectiveFrom = new Date(dto.effectiveFrom);
    if (dto.effectiveTo !== undefined) patch.effectiveTo = new Date(dto.effectiveTo);
    const updated = await this.repository.update(id, patch);
    if (!updated) throw new NotFoundException(`Weight limit rule ${id} not found`);
    return updated;
  }

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