import { Injectable } from '@nestjs/common';
import { DataSource, IsNull } from 'typeorm';

import { Warehouse } from './entities/warehouse.entity';
import { WarehouseInventory } from './entities/warehouse-inventory.entity';

export interface WarehouseDashboard {
  totalWarehouses: number;
  totalInventory: number;
  receivedToday: number;
  // Inspection gate
  awaitingInspection: number;
  inspected: number;
  // Export branch
  stored: number;
  reserved: number;
  readyForLoading: number;
  loaded: number;
  dispatched: number;
  // Import branch
  readyForPickup: number;
  delivered: number;
}

@Injectable()
export class WarehouseDashboardService {
  constructor(private readonly dataSource: DataSource) {}

  async getDashboard(): Promise<WarehouseDashboard> {
    const warehouseRepo = this.dataSource.getRepository(Warehouse);
    const inventoryRepo = this.dataSource.getRepository(WarehouseInventory);

    const startOfToday = new Date();
    startOfToday.setHours(0, 0, 0, 0);

    const [
      totalWarehouses,
      totalInventory,
      awaitingInspection,
      inspected,
      stored,
      reserved,
      readyForLoading,
      loaded,
      dispatched,
      readyForPickup,
      delivered,
      receivedToday,
    ] = await Promise.all([
      warehouseRepo.count(),
      inventoryRepo.count(),
      inventoryRepo.count({ where: { status: 'RECEIVED', inspectionStatus: IsNull() } }),
      inventoryRepo.count({ where: { inspectionStatus: 'PASSED' } }),
      inventoryRepo.count({ where: { status: 'STORED' } }),
      inventoryRepo.count({ where: { status: 'RESERVED' } }),
      inventoryRepo.count({ where: { status: 'READY_FOR_LOADING' } }),
      inventoryRepo.count({ where: { status: 'LOADED' } }),
      inventoryRepo.count({ where: { status: 'DISPATCHED' } }),
      inventoryRepo.count({ where: { status: 'READY_FOR_PICKUP' } }),
      inventoryRepo.count({ where: { status: 'DELIVERED' } }),
      inventoryRepo
        .createQueryBuilder('inv')
        .where('inv.arrived_at >= :start', { start: startOfToday })
        .getCount(),
    ]);

    return {
      totalWarehouses,
      totalInventory,
      receivedToday,
      awaitingInspection,
      inspected,
      stored,
      reserved,
      readyForLoading,
      loaded,
      dispatched,
      readyForPickup,
      delivered,
    };
  }
}
