// AS4 Settlement Provisioning Service
// Provisions AS4 settlement service for marketplace subscriptions

import { v4 as uuidv4 } from 'uuid';
import prisma from '@/shared/database/prisma';
import { memberDirectoryService } from '@/core/settlement/as4-settlement/member-directory/member-directory.service';
import { logger } from '@/infrastructure/monitoring/logger';

export interface As4SettlementProvisioningResult {
  success: boolean;
  memberId?: string;
  as4EndpointUrl?: string;
  error?: string;
}

export class As4SettlementProvisioningService {
  /**
   * Provision AS4 settlement for subscription
   */
  async provision(data: {
    subscriptionId: string;
    organizationName: string;
    capacityTier: number;
    deploymentConfig?: any;
  }): Promise<As4SettlementProvisioningResult> {
    try {
      // Get subscription
      const subscription = await prisma.iruSubscription.findUnique({
        where: { subscriptionId: data.subscriptionId },
        include: {
          inquiry: true,
        },
      });

      if (!subscription) {
        return {
          success: false,
          error: `Subscription ${data.subscriptionId} not found`,
        };
      }

      // Generate member ID
      const memberId = `MEMBER-${subscription.subscriptionId.substring(0, 8).toUpperCase()}`;

      // Check if member already exists
      const existing = await memberDirectoryService.getMember(memberId);
      if (existing) {
        return {
          success: true,
          memberId: existing.memberId,
          as4EndpointUrl: existing.as4EndpointUrl,
        };
      }

      // Generate AS4 endpoint URL
      const as4EndpointUrl = `${process.env.AS4_BASE_URL || 'https://as4.dbis.org'}/api/v1/as4/gateway/messages`;

      // Register member in directory
      const member = await memberDirectoryService.registerMember({
        memberId,
        organizationName: data.organizationName,
        as4EndpointUrl,
        tlsCertFingerprint: '', // Will be set during certificate setup
        allowedMessageTypes: ['DBIS.SI.202', 'DBIS.SI.202COV'],
        routingGroups: ['DEFAULT'],
        capacityTier: data.capacityTier,
      });

      logger.info('AS4 settlement provisioned', {
        subscriptionId: data.subscriptionId,
        memberId: member.memberId,
      });

      return {
        success: true,
        memberId: member.memberId,
        as4EndpointUrl: member.as4EndpointUrl,
      };
    } catch (error) {
      logger.error('AS4 settlement provisioning failed', {
        subscriptionId: data.subscriptionId,
        error: error instanceof Error ? error.message : 'Unknown error',
      });

      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  }
}

export const as4SettlementProvisioningService = new As4SettlementProvisioningService();
