// SDIP Revocation Service

import prisma from '@/shared/database/prisma';
import { SDIPRevocationRequest } from './types';
import { logger } from '@/infrastructure/monitoring/logger';


export class SDIPRevocationService {
  /**
   * Revoke SDIP passport
   */
  async revokePassport(request: SDIPRevocationRequest): Promise<void> {
    const passport = await prisma.sovereign_digital_identity_passports.findUnique({
      where: { passportId: request.passportId },
    });

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

    if (passport.revocationStatus === 'REVOKED') {
      throw new Error(`Passport already revoked: ${request.passportId}`);
    }

    // Update passport status
    await prisma.sovereign_digital_identity_passports.update({
      where: { passportId: request.passportId },
      data: {
        revocationStatus: 'REVOKED',
        updatedAt: new Date(),
      },
    });

    // Create revocation record
    await prisma.sdip_revocations.create({
      data: {
        revocationId: `REV-${request.passportId}-${Date.now()}`,
        passportId: request.passportId,
        reason: request.reason,
        revokedBy: request.revokedBy,
      },
    });

    logger.info(`Revoked SDIP passport: ${request.passportId}`, {
      reason: request.reason,
      revokedBy: request.revokedBy,
    });
  }

  /**
   * Check if passport is revoked
   */
  async isRevoked(passportId: string): Promise<boolean> {
    const passport = await prisma.sovereign_digital_identity_passports.findUnique({
      where: { passportId },
      select: { revocationStatus: true },
    });

    return passport?.revocationStatus === 'REVOKED';
  }

  /**
   * Get revocation history for passport
   */
  async getRevocationHistory(passportId: string) {
    const revocations = await prisma.sdip_revocations.findMany({
      where: { passportId },
      orderBy: { createdAt: 'desc' },
    });

    return revocations;
  }

  /**
   * Get expiring passports (within N days)
   */
  async getExpiringPassports(daysAhead: number = 30) {
    const cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() + daysAhead);

    const passports = await prisma.sovereign_digital_identity_passports.findMany({
      where: {
        expiry: {
          lte: cutoffDate,
        },
        revocationStatus: 'ACTIVE',
      },
      orderBy: { expiry: 'asc' },
    });

    return passports;
  }
}

export const sdipRevocationService = new SDIPRevocationService();

