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';
import type {
  IGetEmployeeIDsByContractIdsQuery,
  IGetEmployeeIdsByDocumentIdsQuery,
  IInsertDeelContractParams,
  IInsertDeelContractQuery,
} from '../types.js';

const getEmployeeIDsByContractIds = sql<IGetEmployeeIDsByContractIdsQuery>`
  SELECT *
  FROM accounter_schema.deel_workers
  WHERE contract_id in $$contractIds;`;

const getEmployeeIdsByDocumentIds = sql<IGetEmployeeIdsByDocumentIdsQuery>`
  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<IInsertDeelContractQuery>`
      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 *;`;

@Injectable({
  scope: Scope.Operation,
  global: true,
})
export class DeelContractsProvider {
  constructor(
    private db: TenantAwareDBClient,
    private adminContextProvider: AdminContextProvider,
  ) {}

  private async batchEmployeeIDsByContractIds(contractIds: readonly string[]) {
    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;
    });
  }

  public getEmployeeIDByContractIdLoader = new DataLoader((contractIds: readonly string[]) =>
    this.batchEmployeeIDsByContractIds(contractIds),
  );
  private async batchEmployeesByContractIds(contractIds: readonly string[]) {
    const contracts = await getEmployeeIDsByContractIds.run({ contractIds }, this.db);
    return contractIds.map(id => contracts.find(contract => contract.contract_id === id));
  }

  public getEmployeeByContractIdLoader = new DataLoader((contractIds: readonly string[]) =>
    this.batchEmployeesByContractIds(contractIds),
  );

  private async batchEmployeeIdsByDocumentIds(documentIds: readonly string[]) {
    const employeeMatches = await getEmployeeIdsByDocumentIds.run({ documentIds }, this.db);
    return documentIds.map(
      documentId =>
        employeeMatches.find(match => match.document_id === documentId)?.business_id ?? null,
    );
  }

  public getEmployeeIdByDocumentIdLoader = new DataLoader((documentIds: readonly string[]) =>
    this.batchEmployeeIdsByDocumentIds(documentIds),
  );

  public async insertDeelContract(params: IInsertDeelContractParams) {
    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 });
    }
  }
}
