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 getEmployeeIDsByContractIds = sql `
  SELECT *
  FROM accounter_schema.deel_workers
  WHERE contract_id in $$contractIds;`;
const getEmployeeIdsByDocumentIds = sql `
  SELECT di.document_id, dw.business_id
  FROM accounter_schema.deel_invoices di
  LEFT JOIN accounter_schema.deel_workers dw
    ON di.contract_id = dw.contract_id
  WHERE di.document_id in $$documentIds;`;
const insertDeelContract = sql `
      INSERT INTO accounter_schema.deel_workers (
        contract_id,
        contractor_id,
        contractor_name,
        contract_start_date,
        business_id,
        owner_id
      )
      VALUES (
        $contractId,
        $contractorId,
        $contractorName,
        $contractStartDate,
        $businessId,
        $ownerId
      )
      RETURNING *;`;
let DeelContractsProvider = class DeelContractsProvider {
    db;
    adminContextProvider;
    constructor(db, adminContextProvider) {
        this.db = db;
        this.adminContextProvider = adminContextProvider;
    }
    async batchEmployeeIDsByContractIds(contractIds) {
        const contracts = await getEmployeeIDsByContractIds.run({ contractIds }, this.db);
        return contractIds.map(id => {
            const businessId = contracts.find(contract => contract.contract_id === id)?.business_id;
            if (!businessId) {
                throw new Error(`Missing businessId for Deel contract ID [${id}]`);
            }
            return businessId;
        });
    }
    getEmployeeIDByContractIdLoader = new DataLoader((contractIds) => this.batchEmployeeIDsByContractIds(contractIds));
    async batchEmployeesByContractIds(contractIds) {
        const contracts = await getEmployeeIDsByContractIds.run({ contractIds }, this.db);
        return contractIds.map(id => contracts.find(contract => contract.contract_id === id));
    }
    getEmployeeByContractIdLoader = new DataLoader((contractIds) => this.batchEmployeesByContractIds(contractIds));
    async batchEmployeeIdsByDocumentIds(documentIds) {
        const employeeMatches = await getEmployeeIdsByDocumentIds.run({ documentIds }, this.db);
        return documentIds.map(documentId => employeeMatches.find(match => match.document_id === documentId)?.business_id ?? null);
    }
    getEmployeeIdByDocumentIdLoader = new DataLoader((documentIds) => this.batchEmployeeIdsByDocumentIds(documentIds));
    async insertDeelContract(params) {
        try {
            const { ownerId } = await this.adminContextProvider.getVerifiedAdminContext();
            // invalidate cache
            return insertDeelContract.run(reassureOwnerIdExists(params, ownerId), this.db);
        }
        catch (e) {
            const message = `Error inserting Deel contract [${params.contractId}]`;
            console.error(`${message}: ${e}`);
            throw new Error(message, { cause: e });
        }
    }
};
DeelContractsProvider = __decorate([
    Injectable({
        scope: Scope.Operation,
        global: true,
    }),
    __metadata("design:paramtypes", [TenantAwareDBClient,
        AdminContextProvider])
], DeelContractsProvider);
export { DeelContractsProvider };
//# sourceMappingURL=deel-contracts.provider.js.map