import { __decorate, __metadata } from "tslib";
import DataLoader from 'dataloader';
import { Injectable, Scope } from 'graphql-modules';
import { sql } from '@pgtyped/runtime';
import { reassureOwnerIdExists } from '../../../shared/helpers/index.js';
import { AdminContextProvider } from '../../admin-context/providers/admin-context.provider.js';
import { TenantAwareDBClient } from '../../app-providers/tenant-db-client.js';
const getDepreciationRecordsByChargeIds = sql `
  SELECT d.*, (d.activation_date + (CONCAT((100 / dc.percentage * 365)::text, ' day'))::interval)::date as expiration_date
  FROM accounter_schema.depreciation d
  LEFT JOIN accounter_schema.depreciation_categories dc
            ON d.category = dc.id
  WHERE d.charge_id IN $$chargeIds;`;
const getDepreciationRecordsByIds = sql `
  SELECT d.*, (d.activation_date + (CONCAT((100 / dc.percentage * 365)::text, ' day'))::interval)::date as expiration_date
  FROM accounter_schema.depreciation d
  LEFT JOIN accounter_schema.depreciation_categories dc
            ON d.category = dc.id
  WHERE d.id IN $$depreciationRecordIds;`;
const getDepreciationRecordsByDates = sql `
  WITH depreciation AS (SELECT d.*,
                              (activation_date +
                              (CONCAT((100 / dc.percentage * 365)::text, ' day'))::interval)::date AS expiration_date
                      FROM accounter_schema.depreciation d
                                LEFT JOIN accounter_schema.depreciation_categories dc
                                          ON d.category = dc.id
                      WHERE activation_date <= $toDate)
  SELECT *
  FROM depreciation
  WHERE expiration_date >= $fromDate;`;
const updateDepreciationRecord = sql `
  UPDATE accounter_schema.depreciation
  SET
  charge_id = COALESCE(
    $chargeId,
    charge_id
  ),
  amount = COALESCE(
    $amount,
    amount
  ),
  currency = COALESCE(
    $currency,
    currency
  ),
  activation_date = COALESCE(
    $activationDate,
    activation_date
  ),
  type = COALESCE(
    $type,
    type
  ),
  category = COALESCE(
    $categoryId,
    category
  )
  WHERE
    id = $id
  RETURNING *;`;
const insertDepreciationRecord = sql `
  INSERT INTO accounter_schema.depreciation (charge_id, amount, currency, activation_date, type, category, owner_id)
  VALUES ($chargeId, $amount, $currency, $activationDate, $type, $categoryId, $ownerId)
  RETURNING *`;
const deleteDepreciationRecord = sql `
  DELETE FROM accounter_schema.depreciation
  WHERE id = $depreciationRecordId
  RETURNING id;
`;
const deleteDepreciationRecordByChargeId = sql `
  DELETE FROM accounter_schema.depreciation
  WHERE charge_id = $chargeId
  RETURNING id;
`;
let DepreciationProvider = class DepreciationProvider {
    db;
    adminContextProvider;
    constructor(db, adminContextProvider) {
        this.db = db;
        this.adminContextProvider = adminContextProvider;
    }
    async batchDepreciationRecordsByIds(depreciationRecordIds) {
        const records = await getDepreciationRecordsByIds.run({
            depreciationRecordIds,
        }, this.db);
        return depreciationRecordIds.map(id => records.find(record => record.id === id));
    }
    getDepreciationRecordByIdLoader = new DataLoader((ids) => this.batchDepreciationRecordsByIds(ids));
    async batchDepreciationRecordsByChargeIds(chargeIds) {
        const records = await getDepreciationRecordsByChargeIds.run({
            chargeIds,
        }, this.db);
        records.map(record => {
            this.getDepreciationRecordByIdLoader.prime(record.id, record);
        });
        return chargeIds.map(id => records.filter(record => record.charge_id === id));
    }
    getDepreciationRecordsByChargeIdLoader = new DataLoader((ids) => this.batchDepreciationRecordsByChargeIds(ids));
    getDepreciationRecordsByDates(params) {
        return getDepreciationRecordsByDates.run(params, this.db).then(records => {
            records.map(record => {
                this.getDepreciationRecordByIdLoader.prime(record.id, record);
            });
            return records;
        });
    }
    updateDepreciationRecord(params) {
        this.clearCache();
        return updateDepreciationRecord.run(params, this.db);
    }
    async insertDepreciationRecord(params) {
        this.clearCache();
        const { ownerId } = await this.adminContextProvider.getVerifiedAdminContext();
        return insertDepreciationRecord.run(reassureOwnerIdExists(params, ownerId), this.db);
    }
    deleteDepreciationRecord(params) {
        this.clearCache();
        return deleteDepreciationRecord.run(params, this.db);
    }
    deleteDepreciationRecordByChargeId(params) {
        this.clearCache();
        return deleteDepreciationRecordByChargeId.run(params, this.db);
    }
    clearCache() {
        this.getDepreciationRecordByIdLoader.clearAll();
        this.getDepreciationRecordsByChargeIdLoader.clearAll();
    }
};
DepreciationProvider = __decorate([
    Injectable({
        scope: Scope.Operation,
        global: true,
    }),
    __metadata("design:paramtypes", [TenantAwareDBClient,
        AdminContextProvider])
], DepreciationProvider);
export { DepreciationProvider };
//# sourceMappingURL=depreciation.provider.js.map