// SDIP Issuer Service - SIF (Sovereign Identity Fabric) Passport Issuance

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { SDIPIssuanceRequest, SDIPPassport, TrustLevel } from './types';
import { quantumCryptoService } from '@/infrastructure/quantum/quantum-crypto.service';
import { logger } from '@/infrastructure/monitoring/logger';


export class SDIPIssuerService {
  /**
   * Issue a new SDIP passport
   */
  async issuePassport(request: SDIPIssuanceRequest): Promise<SDIPPassport> {
    // Verify sovereign issuer exists
    const sovereignBank = await prisma.sovereignBank.findUnique({
      where: { sovereignCode: request.sovereignIssuer },
    });

    if (!sovereignBank) {
      throw new Error(`Sovereign issuer not found: ${request.sovereignIssuer}`);
    }

    // Get sovereign identity for HSM signing
    const sovereignIdentity = await prisma.sovereignIdentity.findFirst({
      where: {
        sovereignBankId: sovereignBank.id,
        identityType: 'Master',
      },
    });

    if (!sovereignIdentity) {
      throw new Error(`Sovereign identity not found for issuer: ${request.sovereignIssuer}`);
    }

    // Generate passport ID
    const passportId = `SDIP-${request.sovereignIssuer}-${uuidv4()}`;

    // Calculate expiry date
    const validityYears = request.validityYears || 1;
    const expiry = new Date();
    expiry.setFullYear(expiry.getFullYear() + validityYears);

    // Generate HSM signature (root cert)
    const rootCert = await this.generateHSMSignature(passportId, sovereignIdentity.hsmKeyId || '');

    // Generate PQ signature (Dilithium)
    const pqSignature = await this.generatePQSignature(passportId, sovereignIdentity.quantumKeyId || '');

    // Create passport record
    const passport = await prisma.sovereignDigitalIdentityPassport.create({
      data: {
        passportId,
        entityType: request.entityType,
        entityId: request.entityId,
        sovereignIssuer: request.sovereignIssuer,
        rootCert,
        pqSignature,
        trustLevel: request.trustLevel,
        expiry,
        revocationStatus: 'ACTIVE',
        attributes: request.attributes || {},
      },
    });

    logger.info(`Issued SDIP passport: ${passportId}`, {
      entityType: request.entityType,
      trustLevel: request.trustLevel,
    });

    return this.mapToSDIPPassport(passport);
  }

  /**
   * Generate HSM signature for root certificate
   */
  private async generateHSMSignature(passportId: string, hsmKeyId: string): Promise<string> {
    // In production, this would use actual HSM
    // For now, generate a mock signature
    const message = `SDIP_ROOT_CERT:${passportId}`;
    return `HSM_SIG:${Buffer.from(message).toString('base64')}`;
  }

  /**
   * Generate PQ signature (Dilithium)
   */
  private async generatePQSignature(passportId: string, quantumKeyId: string): Promise<string> {
    if (!quantumKeyId) {
      // Generate a mock signature if quantum key not available
      const message = `SDIP_PQ_SIG:${passportId}`;
      return `DILITHIUM_SIG:${Buffer.from(message).toString('base64')}`;
    }

    // In production, use quantum crypto service
    const message = `SDIP_PQ_SIG:${passportId}`;
    try {
      // This would use actual Dilithium signing
      return `DILITHIUM_SIG:${Buffer.from(message).toString('base64')}`;
    } catch (error) {
      logger.warn(`PQ signature generation failed, using fallback`, { quantumKeyId });
      return `DILITHIUM_SIG:${Buffer.from(message).toString('base64')}`;
    }
  }

  /**
   * Renew passport
   */
  async renewPassport(passportId: string, validityYears?: number): Promise<SDIPPassport> {
    const existing = await prisma.sovereignDigitalIdentityPassport.findUnique({
      where: { passportId },
    });

    if (!existing) {
      throw new Error(`Passport not found: ${passportId}`);
    }

    if (existing.revocationStatus === 'REVOKED') {
      throw new Error(`Cannot renew revoked passport: ${passportId}`);
    }

    // Calculate new expiry
    const validity = validityYears || 1;
    const newExpiry = new Date();
    newExpiry.setFullYear(newExpiry.getFullYear() + validity);

    // Regenerate signatures
    const sovereignIdentity = await prisma.sovereignIdentity.findFirst({
      where: {
        sovereignBank: {
          sovereignCode: existing.sovereignIssuer,
        },
        identityType: 'Master',
      },
    });

    const rootCert = await this.generateHSMSignature(passportId, sovereignIdentity?.hsmKeyId || '');
    const pqSignature = await this.generatePQSignature(passportId, sovereignIdentity?.quantumKeyId || '');

    const renewed = await prisma.sovereignDigitalIdentityPassport.update({
      where: { passportId },
      data: {
        rootCert,
        pqSignature,
        expiry: newExpiry,
        updatedAt: new Date(),
      },
    });

    logger.info(`Renewed SDIP passport: ${passportId}`);

    return this.mapToSDIPPassport(renewed);
  }

  private mapToSDIPPassport(passport: any): SDIPPassport {
    return {
      id: passport.id,
      passportId: passport.passportId,
      entityType: passport.entityType as any,
      entityId: passport.entityId,
      sovereignIssuer: passport.sovereignIssuer,
      rootCert: passport.rootCert,
      pqSignature: passport.pqSignature,
      trustLevel: passport.trustLevel as TrustLevel,
      expiry: passport.expiry,
      revocationStatus: passport.revocationStatus as any,
      attributes: passport.attributes as Record<string, unknown>,
      createdAt: passport.createdAt,
      updatedAt: passport.updatedAt,
    };
  }
}

export const sdipIssuerService = new SDIPIssuerService();

