import { __decorate, __metadata } from "tslib";
import DataLoader from 'dataloader';
import { Injectable, Scope } from 'graphql-modules';
import { sql } from '@pgtyped/runtime';
import { TenantAwareDBClient } from '../../app-providers/tenant-db-client.js';
const getTransactionsByIds = sql `
    SELECT *
    FROM accounter_schema.transactions
    WHERE id IN $$transactionIds;`;
const getTransactionsByChargeIds = sql `
    SELECT *
    FROM accounter_schema.transactions
    WHERE charge_id IN $$chargeIds;`;
const getTransactionsByMissingRequiredInfo = sql `
    SELECT *
    FROM accounter_schema.transactions
    WHERE business_id IS NULL;`;
const getTransactionsByFilters = sql `
  SELECT *
  FROM accounter_schema.transactions
  WHERE
    ($isIDs = 0 OR id IN $$IDs)
    AND ($fromEventDate ::TEXT IS NULL OR event_date::TEXT::DATE >= date_trunc('day', $fromEventDate ::DATE))
    AND ($toEventDate ::TEXT IS NULL OR event_date::TEXT::DATE <= date_trunc('day', $toEventDate ::DATE))
    AND ($fromDebitDate ::TEXT IS NULL OR COALESCE(debit_date_override, debit_date)::TEXT::DATE >= date_trunc('day', $fromDebitDate ::DATE))
    AND ($toDebitDate ::TEXT IS NULL OR COALESCE(debit_date_override, debit_date)::TEXT::DATE <= date_trunc('day', $toDebitDate ::DATE))
    AND ($isBusinessIDs = 0 OR business_id IN $$businessIDs)
    AND ($isOwnerIDs = 0 OR owner_id IN $$ownerIDs)
  ORDER BY event_date DESC;
`;
const getSimilarTransactions = sql `
    SELECT *
    FROM accounter_schema.transactions
    WHERE (CASE WHEN $withMissingInfo IS TRUE THEN
      business_id IS NULL
   ELSE
      TRUE
   END)
      AND (
        (source_description IS NOT NULL AND source_description <> '' AND source_description = $details)
        OR (counter_account IS NOT NULL AND counter_account <> '' AND counter_account = $counterAccount)
      ) AND owner_id = $ownerId;`;
const replaceTransactionsChargeId = sql `
  UPDATE accounter_schema.transactions
  SET charge_id = $assertChargeID
  WHERE charge_id = $replaceChargeID
  RETURNING id;
`;
const updateTransactions = sql `
  UPDATE accounter_schema.transactions
  SET
    account_id = COALESCE(
      $accountId,
      account_id,
      NULL
    ),
    charge_id = COALESCE(
      $chargeId,
      charge_id,
      NULL
    ),
    debit_date_override = COALESCE(
      $debitDate,
      debit_date_override,
      NULL
    ),
    business_id = COALESCE(
      $businessId,
      business_id,
      NULL
    ),
    is_fee = COALESCE(
      $isFee,
      is_fee,
      NULL
    )
  WHERE
    id IN $$transactionIds
  RETURNING *;
`;
let TransactionsProvider = class TransactionsProvider {
    db;
    constructor(db) {
        this.db = db;
    }
    async batchTransactionsByIds(ids) {
        const transactionIds = Array.from(new Set(ids));
        const transactions = await getTransactionsByIds.run({
            transactionIds,
        }, this.db);
        return ids.map(id => {
            const transaction = transactions.find(transaction => transaction.id === id);
            if (!transaction) {
                return new Error(`Transaction ID="${id}" not found`);
            }
            return transaction;
        });
    }
    transactionByIdLoader = new DataLoader((keys) => this.batchTransactionsByIds(keys));
    async getTransactionsByMissingRequiredInfo() {
        return getTransactionsByMissingRequiredInfo.run(undefined, this.db).then(res => res.map(t => {
            this.transactionByIdLoader.prime(t.id, t);
            return t;
        }));
    }
    async batchTransactionsByChargeIDs(chargeIds) {
        const transactions = await getTransactionsByChargeIds.run({
            chargeIds,
        }, this.db);
        transactions.map(t => {
            this.transactionByIdLoader.prime(t.id, t);
        });
        return chargeIds.map(id => transactions.filter(transaction => transaction.charge_id === id));
    }
    transactionsByChargeIDLoader = new DataLoader((keys) => this.batchTransactionsByChargeIDs(keys));
    getTransactionsByFilters(params) {
        const isIDs = !!params?.IDs?.length;
        const isBusinessIDs = !!params?.businessIDs?.length;
        const isOwnerIDs = !!params?.ownerIDs?.length;
        const fullParams = {
            isIDs: isIDs ? 1 : 0,
            isBusinessIDs: isBusinessIDs ? 1 : 0,
            isOwnerIDs: isOwnerIDs ? 1 : 0,
            fromEventDate: null,
            toEventDate: null,
            fromDebitDate: null,
            toDebitDate: null,
            ...params,
            IDs: isIDs ? params.IDs : [null],
            businessIDs: isBusinessIDs ? params.businessIDs : [null],
            ownerIDs: isOwnerIDs ? params.ownerIDs : [null],
        };
        return getTransactionsByFilters.run(fullParams, this.db);
    }
    async getSimilarTransactions(params) {
        try {
            return getSimilarTransactions.run(params, this.db);
        }
        catch (error) {
            const message = 'Failed to fetch similar transactions';
            console.error(message, error);
            throw new Error(message, { cause: error });
        }
    }
    async replaceTransactionsChargeId(params) {
        if (params.replaceChargeID) {
            await this.invalidateTransactionByChargeID(params.replaceChargeID);
        }
        if (params.assertChargeID) {
            await this.invalidateTransactionByChargeID(params.assertChargeID);
        }
        return replaceTransactionsChargeId.run(params, this.db);
    }
    async updateTransactions(params) {
        if (params.transactionIds) {
            await Promise.all(params.transactionIds.map(async (id) => {
                if (id) {
                    await this.invalidateTransactionByID(id);
                }
            }));
        }
        return updateTransactions.run(params, this.db);
    }
    async invalidateTransactionByChargeID(chargeId) {
        this.transactionsByChargeIDLoader.clear(chargeId);
        try {
            const transactions = await getTransactionsByChargeIds.run({
                chargeIds: [chargeId],
            }, this.db);
            transactions.map(t => this.transactionByIdLoader.clear(t.id));
        }
        catch (e) {
            console.error(`Error invalidating transaction by charge ID "${chargeId}":`, e);
        }
    }
    async invalidateTransactionByID(id) {
        this.transactionByIdLoader.clear(id);
        try {
            const [transaction] = await getTransactionsByIds.run({
                transactionIds: [id],
            }, this.db);
            if (transaction?.charge_id) {
                this.transactionsByChargeIDLoader.clear(transaction.charge_id);
            }
        }
        catch (e) {
            console.error(`Error invalidating transaction by ID "${id}":`, e);
        }
    }
    clearCache() {
        this.transactionByIdLoader.clearAll();
        this.transactionsByChargeIDLoader.clearAll();
    }
};
TransactionsProvider = __decorate([
    Injectable({
        scope: Scope.Operation,
        global: true,
    }),
    __metadata("design:paramtypes", [TenantAwareDBClient])
], TransactionsProvider);
export { TransactionsProvider };
//# sourceMappingURL=transactions.provider.js.map