import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { BaseRepository } from '@edr/api-common';
import { Repository, Between } from 'typeorm';
import { FuelPurchase } from './entities/fuel-purchase.entity';
import { FuelConsumption } from './entities/fuel-consumption.entity';

@Injectable()
export class FuelRepository extends BaseRepository<FuelPurchase> {
  constructor(
    @InjectRepository(FuelPurchase)
    private readonly purchaseRepository: Repository<FuelPurchase>,
    @InjectRepository(FuelConsumption)
    private readonly consumptionRepository: Repository<FuelConsumption>,
  ) {
    super(purchaseRepository);
  }

  async findByVehicleAndDateRange(
    vehicleId: string,
    startDate: Date,
    endDate: Date,
  ): Promise<FuelPurchase[]> {
    return this.purchaseRepository.find({
      where: {
        vehicleId,
        purchaseDate: Between(startDate, endDate),
      },
      order: { purchaseDate: 'DESC' },
    });
  }

  async getMonthlyConsumption(
    vehicleId: string,
    month: Date,
  ): Promise<FuelConsumption | null> {
    return this.consumptionRepository.findOne({
      where: {
        vehicleId,
        month,
      },
    });
  }

  async updateMonthlyConsumption(
    vehicleId: string,
    month: Date,
    data: Partial<FuelConsumption>,
  ): Promise<FuelConsumption> {
    let consumption = await this.consumptionRepository.findOne({
      where: {
        vehicleId,
        month,
      },
    });

    if (!consumption) {
      consumption = this.consumptionRepository.create({
        vehicleId,
        month,
        ...data,
      });
    } else {
      Object.assign(consumption, data);
    }

    return this.consumptionRepository.save(consumption);
  }

  async findPurchasesByVehicle(vehicleId: string): Promise<FuelPurchase[]> {
    return this.purchaseRepository.find({
      where: { vehicleId },
      order: { purchaseDate: 'DESC' },
    });
  }
}
