// Global Ledger State Validation Service

import { createHash } from 'crypto';
import prisma from '@/shared/database/prisma';


export class NceStateService {
  /**
   * Validate state block integrity
   */
  async validateStateIntegrity(ledgerStateHash: string): Promise<boolean> {
    // In production, this would:
    // 1. Retrieve the actual ledger state
    // 2. Calculate hash
    // 3. Compare with provided hash
    // 4. Verify block chain integrity

    // For now, perform basic validation
    if (!ledgerStateHash || ledgerStateHash.length < 32) {
      return false;
    }

    // Check if state exists in consensus records
    const existingState = await prisma.neuralConsensusState.findFirst({
      where: {
        ledgerStateHash,
        status: 'confirmed',
      },
    });

    // If state exists and is confirmed, integrity is valid
    if (existingState) {
      return true;
    }

    // For new states, validate hash format
    // SHA-256 hash should be 64 hex characters
    const hashPattern = /^[a-f0-9]{64}$/i;
    return hashPattern.test(ledgerStateHash);
  }

  /**
   * Calculate state hash
   */
  calculateStateHash(stateData: Record<string, unknown>): string {
    const stateString = JSON.stringify(stateData);
    return createHash('sha256').update(stateString).digest('hex');
  }

  /**
   * Verify state block integrity
   */
  async verifyStateBlock(
    ledgerStateHash: string,
    previousHash?: string
  ): Promise<{
    valid: boolean;
    errors: string[];
  }> {
    const errors: string[] = [];

    // Validate hash format
    if (!this.validateStateIntegrity(ledgerStateHash)) {
      errors.push('Invalid state hash format');
    }

    // If previous hash provided, verify chain
    if (previousHash) {
      const previousState = await prisma.neuralConsensusState.findFirst({
        where: {
          ledgerStateHash: previousHash,
          status: 'confirmed',
        },
      });

      if (!previousState) {
        errors.push('Previous state not found or not confirmed');
      }
    }

    return {
      valid: errors.length === 0,
      errors,
    };
  }
}

export const nceStateService = new NceStateService();

