// Commodities Engine

import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { subLedgerService } from '@/core/ledger/subledgers/subledger.service';


export class CommoditiesService {
  /**
   * Update commodity spot price
   */
  async updateSpotPrice(
    commodityType: string,
    unit: string,
    spotPrice: string,
    priceSource: string
  ): Promise<void> {
    await prisma.commodity.upsert({
      where: {
        commodityType_unit: {
          commodityType,
          unit,
        },
      },
      update: {
        spotPrice: new Decimal(spotPrice),
        priceSource,
        lastUpdated: new Date(),
      },
      create: {
        commodityType,
        unit,
        spotPrice: new Decimal(spotPrice),
        priceSource,
        lastUpdated: new Date(),
      },
    });
  }

  /**
   * Create commodity sub-ledger entry
   */
  async createCommodityEntry(
    ledgerEntryId: string,
    commodityType: string,
    quantity: string,
    unit: string,
    price?: string
  ): Promise<void> {
    await subLedgerService.createCommoditiesSubLedgerEntry(
      ledgerEntryId,
      commodityType,
      quantity,
      unit,
      price
    );
  }
}

export const commoditiesService = new CommoditiesService();

