// DBIS Sovereign Contract Fabric (DCF)

import { Prisma } from '@prisma/client';
import prisma from '@/shared/database/prisma';
import {
  SmartContract,
  ContractTemplateType,
  ContractState,
} from '@/shared/types';
import { v4 as uuidv4 } from 'uuid';


export class ContractFabricService {
  /**
   * Create smart contract
   */
  async createContract(
    sovereignBankId: string,
    templateType: ContractTemplateType,
    parameters: Record<string, unknown>,
    signatories: string[]
  ): Promise<SmartContract> {
    const contractId = `CONTRACT-${uuidv4()}`;

    const contract = await prisma.smart_contracts.create({
      data: {
        id: uuidv4(),
        contractId,
        sovereignBankId,
        templateType,
        contractState: ContractState.DRAFT,
        parameters: parameters as Prisma.InputJsonValue,
        signatories: signatories as Prisma.InputJsonValue,
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    return this.mapToSmartContract(contract);
  }

  /**
   * Execute contract
   */
  async executeContract(contractId: string, executionResult: Record<string, unknown>): Promise<void> {
    await prisma.smart_contracts.update({
      where: { contractId },
      data: {
        contractState: ContractState.EXECUTED,
        executionResult: executionResult as Prisma.InputJsonValue,
        executedAt: new Date(),
      },
    });
  }

  /**
   * Map Prisma model to SmartContract type
   */
  private mapToSmartContract(contract: any): SmartContract {
    return {
      id: contract.id,
      contractId: contract.contractId,
      sovereignBankId: contract.sovereignBankId,
      templateType: contract.templateType as ContractTemplateType,
      contractState: contract.contractState as ContractState,
      parameters: contract.parameters as Record<string, unknown>,
      signatories: contract.signatories as string[],
      signatures: contract.signatures as Record<string, string> | undefined,
      executionResult: contract.executionResult as Record<string, unknown> | undefined,
    };
  }
}

export const contractFabricService = new ContractFabricService();

