import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';

import { CreateWarehouseZoneDto } from './dto/create-warehouse-zone.dto';
import { UpdateWarehouseZoneDto } from './dto/update-warehouse-zone.dto';
import { WarehouseZone } from './entities/warehouse-zone.entity';
import { WarehouseYardsService } from './warehouse-yards.service';
import { WarehouseZonesRepository } from './warehouse-zones.repository';

@Injectable()
export class WarehouseZonesService {
  constructor(
    private readonly zonesRepository: WarehouseZonesRepository,
    private readonly yardsService: WarehouseYardsService,
  ) {}

  findAll(): Promise<WarehouseZone[]> {
    return this.zonesRepository.findAll({
      relations: { yard: { warehouse: true } },
      order: { code: 'ASC' },
    });
  }

  findByYard(yardId: string): Promise<WarehouseZone[]> {
    return this.zonesRepository.findAll({
      where: { yardId },
      order: { code: 'ASC' },
    });
  }

  async findById(id: string): Promise<WarehouseZone> {
    const zone = await this.zonesRepository.findById(id, {
      relations: { yard: { warehouse: true } },
    });

    if (!zone) {
      throw new NotFoundException(`Warehouse zone ${id} not found`);
    }

    return zone;
  }

  async create(yardId: string, dto: CreateWarehouseZoneDto): Promise<WarehouseZone> {
    // Ensure the parent yard exists.
    await this.yardsService.findById(yardId);
    await this.assertCodeUnique(yardId, dto.code.trim());
    await this.assertCapacityWithinYard(yardId, dto.capacityWeight ?? null, dto.capacityContainers ?? null);

    return this.zonesRepository.create({
      yardId,
      name: dto.name.trim(),
      code: dto.code.trim(),
      type: dto.type,
      capacityWeight: dto.capacityWeight ?? null,
      capacityContainers: dto.capacityContainers ?? null,
      maxWeight: dto.maxWeight ?? dto.capacityWeight ?? null,
      maxVolume: dto.maxVolume ?? null,
      currentWeight: 0,
      currentContainers: 0,
      currentVolume: 0,
      status: 'ACTIVE',
      isActive: true,
    });
  }

  async update(id: string, dto: UpdateWarehouseZoneDto): Promise<WarehouseZone> {
    const existing = await this.findById(id);

    if (dto.code && dto.code.trim() !== existing.code) {
      await this.assertCodeUnique(existing.yardId, dto.code.trim(), id);
    }

    const newCapacityWeight = dto.capacityWeight ?? existing.capacityWeight ?? null;
    const newCapacityContainers = dto.capacityContainers ?? existing.capacityContainers ?? null;

    // Validate updated capacity doesn't exceed yard limits
    if (newCapacityWeight !== (existing.capacityWeight ?? null) || newCapacityContainers !== (existing.capacityContainers ?? null)) {
      await this.assertCapacityWithinYard(existing.yardId, newCapacityWeight, newCapacityContainers, id);
    }

    const status = dto.status ?? existing.status;

    const updated = await this.zonesRepository.update(id, {
      name: dto.name?.trim() ?? existing.name,
      code: dto.code?.trim() ?? existing.code,
      type: dto.type ?? existing.type,
      capacityWeight: newCapacityWeight,
      capacityContainers: newCapacityContainers,
      maxWeight: dto.maxWeight ?? existing.maxWeight,
      maxVolume: dto.maxVolume ?? existing.maxVolume,
      status,
      isActive: status === 'ACTIVE',
    });

    if (!updated) {
      throw new NotFoundException(`Warehouse zone ${id} not found`);
    }

    return this.findById(id);
  }

  private async assertCodeUnique(yardId: string, code: string, ignoreId?: string): Promise<void> {
    const [existing] = await this.zonesRepository.findAll({ where: { yardId, code } });

    if (existing && existing.id !== ignoreId) {
      throw new ConflictException(`Zone code ${code} already exists in this yard`);
    }
  }

  private async assertCapacityWithinYard(
    yardId: string,
    newCapacityWeight: number | null,
    newCapacityContainers: number | null,
    excludeZoneId?: string,
  ): Promise<void> {
    const yard = await this.yardsService.findById(yardId);
    const zones = await this.findByYard(yardId);

    // Sum existing zone capacities, excluding the zone being updated if provided
    const otherZones = excludeZoneId ? zones.filter((z) => z.id !== excludeZoneId) : zones;
    const totalExistingWeight = otherZones.reduce((sum, z) => sum + (z.capacityWeight ?? 0), 0);
    const totalExistingContainers = otherZones.reduce((sum, z) => sum + (z.capacityContainers ?? 0), 0);

    // Check weight capacity
    if (newCapacityWeight !== null && yard.capacityWeight != null) {
      const totalWeight = totalExistingWeight + newCapacityWeight;
      if (totalWeight > yard.capacityWeight) {
        throw new BadRequestException(
          `Total zone weight capacity (${totalWeight}t) exceeds yard limit (${yard.capacityWeight}t)`,
        );
      }
    }

    // Check container capacity
    if (newCapacityContainers !== null && yard.capacityContainers != null) {
      const totalContainers = totalExistingContainers + newCapacityContainers;
      if (totalContainers > yard.capacityContainers) {
        throw new BadRequestException(
          `Total zone container capacity (${totalContainers}) exceeds yard limit (${yard.capacityContainers})`,
        );
      }
    }
  }
}
