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

import { CreateWarehouseYardDto } from './dto/create-warehouse-yard.dto';
import { UpdateWarehouseYardDto } from './dto/update-warehouse-yard.dto';
import { WarehouseYard } from './entities/warehouse-yard.entity';
import { WarehouseYardsRepository } from './warehouse-yards.repository';
import { WarehousesService } from './warehouses.service';

@Injectable()
export class WarehouseYardsService {
  constructor(
    private readonly yardsRepository: WarehouseYardsRepository,
    private readonly warehousesService: WarehousesService,
  ) {}

  findByWarehouse(warehouseId: string): Promise<WarehouseYard[]> {
    return this.yardsRepository.findAll({
      where: { warehouseId },
      relations: { zones: true },
      order: { code: 'ASC' },
    });
  }

  async findById(id: string): Promise<WarehouseYard> {
    const yard = await this.yardsRepository.findById(id, {
      relations: { warehouse: true, zones: true },
    });

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

    return yard;
  }

  async create(warehouseId: string, dto: CreateWarehouseYardDto): Promise<WarehouseYard> {
    // Ensure the parent warehouse exists.
    await this.warehousesService.findById(warehouseId);
    await this.assertCodeUnique(warehouseId, dto.code.trim());

    return this.yardsRepository.create({
      warehouseId,
      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: UpdateWarehouseYardDto): Promise<WarehouseYard> {
    const existing = await this.findById(id);

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

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

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

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

    return this.findById(id);
  }

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

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