/**
 * Azure Logic Apps workflow integration
 * Pre-built workflows for eIDAS-Verify-And-Issue, Appointment-Credential, Batch-Renewal, Document-Attestation
 */

import { AzureLogicAppsClient } from '@the-order/auth';
import { getEnv } from '@the-order/shared';

export interface LogicAppsWorkflowConfig {
  eidasVerifyAndIssueUrl?: string;
  appointmentCredentialUrl?: string;
  batchRenewalUrl?: string;
  documentAttestationUrl?: string;
}

/**
 * Initialize Azure Logic Apps workflows
 */
export function initializeLogicAppsWorkflows(
  config?: LogicAppsWorkflowConfig
): {
  eidasVerifyAndIssue: (eidasData: unknown) => Promise<unknown>;
  appointmentCredential: (appointmentData: unknown) => Promise<unknown>;
  batchRenewal: (renewalData: unknown) => Promise<unknown>;
  documentAttestation: (documentData: unknown) => Promise<unknown>;
} {
  const env = getEnv();

  const eidasClient = config?.eidasVerifyAndIssueUrl
    ? new AzureLogicAppsClient({
        workflowUrl: config.eidasVerifyAndIssueUrl,
        accessKey: env.AZURE_LOGIC_APPS_ACCESS_KEY,
        managedIdentityClientId: env.AZURE_LOGIC_APPS_MANAGED_IDENTITY_CLIENT_ID,
      })
    : null;

  const appointmentClient = config?.appointmentCredentialUrl
    ? new AzureLogicAppsClient({
        workflowUrl: config.appointmentCredentialUrl,
        accessKey: env.AZURE_LOGIC_APPS_ACCESS_KEY,
        managedIdentityClientId: env.AZURE_LOGIC_APPS_MANAGED_IDENTITY_CLIENT_ID,
      })
    : null;

  const batchRenewalClient = config?.batchRenewalUrl
    ? new AzureLogicAppsClient({
        workflowUrl: config.batchRenewalUrl,
        accessKey: env.AZURE_LOGIC_APPS_ACCESS_KEY,
        managedIdentityClientId: env.AZURE_LOGIC_APPS_MANAGED_IDENTITY_CLIENT_ID,
      })
    : null;

  const documentAttestationClient = config?.documentAttestationUrl
    ? new AzureLogicAppsClient({
        workflowUrl: config.documentAttestationUrl,
        accessKey: env.AZURE_LOGIC_APPS_ACCESS_KEY,
        managedIdentityClientId: env.AZURE_LOGIC_APPS_MANAGED_IDENTITY_CLIENT_ID,
      })
    : null;

  return {
    /**
     * eIDAS Verify and Issue workflow
     * Verifies eIDAS signature and issues corresponding credential
     */
    async eidasVerifyAndIssue(eidasData: unknown): Promise<unknown> {
      if (!eidasClient) {
        throw new Error('eIDAS Verify and Issue workflow not configured');
      }

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const eidasDataTyped = eidasData as any;
      return eidasClient.triggerEIDASVerification(
        eidasDataTyped.documentId || '',
        eidasDataTyped.userId || '',
        eidasDataTyped.eidasProviderUrl || ''
      );
    },

    /**
     * Appointment Credential workflow
     * Issues credential based on appointment data
     */
    async appointmentCredential(appointmentData: unknown): Promise<unknown> {
      if (!appointmentClient) {
        throw new Error('Appointment Credential workflow not configured');
      }

      return appointmentClient.triggerWorkflow({
        body: {
          eventType: 'appointmentCredential',
          data: appointmentData,
        },
      });
    },

    /**
     * Batch Renewal workflow
     * Renews multiple credentials in batch
     */
    async batchRenewal(renewalData: unknown): Promise<unknown> {
      if (!batchRenewalClient) {
        throw new Error('Batch Renewal workflow not configured');
      }

      return batchRenewalClient.triggerWorkflow({
        body: {
          eventType: 'batchRenewal',
          data: renewalData,
        },
      });
    },

    /**
     * Document Attestation workflow
     * Attests to document authenticity and issues credential
     */
    async documentAttestation(documentData: unknown): Promise<unknown> {
      if (!documentAttestationClient) {
        throw new Error('Document Attestation workflow not configured');
      }

      return documentAttestationClient.triggerWorkflow({
        body: {
          eventType: 'documentAttestation',
          data: documentData,
        },
      });
    },
  };
}

/**
 * Get default Logic Apps workflows
 */
let defaultWorkflows: ReturnType<typeof initializeLogicAppsWorkflows> | null = null;

export function getLogicAppsWorkflows(
  config?: LogicAppsWorkflowConfig
): ReturnType<typeof initializeLogicAppsWorkflows> {
  if (!defaultWorkflows) {
    defaultWorkflows = initializeLogicAppsWorkflows(config);
  }
  return defaultWorkflows;
}

