// HelloSign Integration Service
// Integration with HelloSign API for e-signatures

import { retryWithBackoff } from '@/shared/utils/retry';
import { logger } from '@/infrastructure/monitoring/logger';

export interface HelloSignRequest {
  agreementId: string;
  signers: Array<{
    name: string;
    email: string;
    role: 'dbis' | 'participant';
    order: number;
  }>;
}

export interface HelloSignResult {
  signatureRequestId: string;
  status: string;
  signerStatus: Array<{
    email: string;
    status: string;
    signedAt?: Date;
  }>;
}

export class HelloSignIntegration {
  /**
   * Create HelloSign signature request
   */
  async createSignatureRequest(request: HelloSignRequest): Promise<HelloSignResult> {
    const hellosignApiKey = process.env.HELLOSIGN_API_KEY;
    if (!hellosignApiKey) {
      throw new Error('HELLOSIGN_API_KEY environment variable is required');
    }

    const hellosignApiBase = process.env.HELLOSIGN_API_BASE || 'https://api.hellosign.com/v3';

    // Get agreement content
    const agreementContent = await this.getAgreementContent(request.agreementId);

    // Create signature request
    const signatureRequest = {
      test_mode: process.env.NODE_ENV !== 'production',
      title: 'IRU Participation Agreement',
      subject: 'IRU Participation Agreement - Signature Required',
      message: 'Please sign the IRU Participation Agreement',
      signers: request.signers.map((signer) => ({
        email_address: signer.email,
        name: signer.name,
        order: signer.order,
      })),
      files: [
        {
          name: 'IRU Participation Agreement.pdf',
          file_url: agreementContent, // In production, this would be a URL to the document
        },
      ],
    };

    const response = await retryWithBackoff(
      async () => {
        return await fetch(`${hellosignApiBase}/signature_request/send`, {
          method: 'POST',
          headers: {
            'Authorization': `Basic ${Buffer.from(hellosignApiKey + ':').toString('base64')}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(signatureRequest),
        });
      },
      {
        maxRetries: 3,
        initialDelayMs: 1000,
        onRetry: (attempt, error) => {
          logger.warn('HelloSign API retry', {
            attempt,
            error: error.message,
          });
        },
      }
    );

    if (!response.ok) {
      const error = await response.json();
      throw new Error(`HelloSign API error: ${error.error?.msg || 'Unknown error'}`);
    }

    const data = await response.json();

    return {
      signatureRequestId: data.signature_request.signature_request_id,
      status: data.signature_request.is_complete ? 'completed' : 'pending',
      signerStatus: data.signature_request.signatures?.map((sig: { signer_email_address: string; status_code: string; signed_at?: number }) => ({
        email: sig.signer_email_address,
        status: sig.status_code,
        signedAt: sig.signed_at ? new Date(sig.signed_at * 1000) : undefined,
      })) || [],
    };
  }

  /**
   * Get HelloSign signature request status
   */
  async getSignatureRequestStatus(signatureRequestId: string): Promise<HelloSignResult> {
    const hellosignApiKey = process.env.HELLOSIGN_API_KEY;
    if (!hellosignApiKey) {
      throw new Error('HELLOSIGN_API_KEY environment variable is required');
    }

    const hellosignApiBase = process.env.HELLOSIGN_API_BASE || 'https://api.hellosign.com/v3';

    const response = await retryWithBackoff(
      async () => {
        return await fetch(`${hellosignApiBase}/signature_request/${signatureRequestId}`, {
          headers: {
            'Authorization': `Basic ${Buffer.from(hellosignApiKey + ':').toString('base64')}`,
          },
        });
      },
      {
        maxRetries: 3,
        initialDelayMs: 1000,
      }
    );

    if (!response.ok) {
      throw new Error(`HelloSign API error: ${response.status} ${response.statusText}`);
    }

    const data = await response.json();
    const signatureRequest = data.signature_request;

    return {
      signatureRequestId: signatureRequest.signature_request_id,
      status: signatureRequest.is_complete ? 'completed' : 'pending',
      signerStatus: signatureRequest.signatures?.map((sig: { signer_email_address: string; status_code: string; signed_at?: number }) => ({
        email: sig.signer_email_address,
        status: sig.status_code,
        signedAt: sig.signed_at ? new Date(sig.signed_at * 1000) : undefined,
      })) || [],
    };
  }

  /**
   * Get agreement content
   */
  private async getAgreementContent(agreementId: string): Promise<string> {
    // Fetch from database
    const { default: prisma } = await import('@/shared/database/prisma');
    
    const agreement = await prisma.iruAgreement.findUnique({
      where: { agreementId },
      select: { agreementContent: true },
    });

    if (agreement?.agreementContent) {
      return agreement.agreementContent;
    }

    // Fallback to default template if not found
    return 'IRU Participation Agreement content...';
  }
}

export const hellosignIntegration = new HelloSignIntegration();
