// PSG Master Grid Service
// Global ledger orchestrator, finality controller, quantum-grade consensus engine

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';


export class PsgMasterGridService {
  /**
   * Initialize or get master grid
   */
  async initializeMasterGrid() {
    const existing = await prisma.psg_master_grids.findFirst({
      where: { status: 'active' },
    });

    if (existing) {
      return existing;
    }

    return await prisma.psg_master_grids.create({
      data: {
        gridId: `GRID-${uuidv4()}`,
        gridName: 'DBIS Master Grid',
        consensusEngine: 'quantum_grade_consensus',
        status: 'active',
      },
    });
  }

  /**
   * Update consensus timestamp
   */
  async updateConsensus() {
    const grid = await this.initializeMasterGrid();

    return await prisma.psg_master_grids.update({
      where: { id: grid.id },
      data: {
        lastConsensusAt: new Date(),
      },
    });
  }

  /**
   * Get master grid status
   */
  async getGridStatus() {
    const grid = await this.initializeMasterGrid();

    const epochs = await prisma.settlement_epochs.findMany({
      where: {
        gridId: grid.gridId,
      },
      orderBy: {
        committedAt: 'desc',
      },
      take: 10,
    });

    return {
      gridId: grid.gridId,
      status: grid.status,
      lastConsensusAt: grid.lastConsensusAt,
      recentEpochs: epochs.length,
      consensusEngine: grid.consensusEngine,
    };
  }
}

export const psgMasterGridService = new PsgMasterGridService();

