import { Injectable } from '@nestjs/common';
import { EntityManager } from 'typeorm';

import {
  WarehouseActivityLog,
  WarehouseActivityType,
} from './entities/warehouse-activity-log.entity';
import { WarehouseActivityLogRepository } from './warehouse-activity-log.repository';

interface LogInput {
  activityType: WarehouseActivityType;
  description?: string;
  inventoryId?: string | null;
  warehouseId?: string | null;
  performedBy?: string | null;
}

@Injectable()
export class WarehouseActivityLogService {
  constructor(private readonly logRepository: WarehouseActivityLogRepository) {}

  /** Persist an activity record. Pass a transaction manager to enrol in the caller's transaction. */
  async record(input: LogInput, manager?: EntityManager): Promise<void> {
    const data = {
      activityType: input.activityType,
      description: input.description ?? null,
      inventoryId: input.inventoryId ?? null,
      warehouseId: input.warehouseId ?? null,
      performedBy: input.performedBy ?? 'system',
    };

    if (manager) {
      await manager.getRepository(WarehouseActivityLog).save(
        manager.getRepository(WarehouseActivityLog).create(data),
      );
      return;
    }

    await this.logRepository.create(data);
  }

  findByInventory(inventoryId: string): Promise<WarehouseActivityLog[]> {
    return this.logRepository.findAll({
      where: { inventoryId },
      order: { createdAt: 'DESC' },
    });
  }
}
