// ISP Node Service
// Planetary sovereign node management

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


export interface CreateNodeRequest {
  planetaryLocation: string; // earth, lunar, martian
  sovereignBankId?: string;
  nodeType: string; // scb, sovereign_authority, economic_council
  nodeName: string;
  nodeAddress: string;
}

export interface NodeResult {
  nodeId: string;
  status: string;
}

export class IspNodeService {
  /**
   * Create interplanetary node
   */
  async createNode(request: CreateNodeRequest): Promise<NodeResult> {
    const nodeId = `ISP-NODE-${uuidv4()}`;

    const node = await prisma.interplanetaryNode.create({
      data: {
        nodeId,
        planetaryLocation: request.planetaryLocation,
        sovereignBankId: request.sovereignBankId || null,
        nodeType: request.nodeType,
        nodeName: request.nodeName,
        nodeAddress: request.nodeAddress,
        status: 'active',
      },
    });

    return {
      nodeId: node.nodeId,
      status: node.status,
    };
  }

  /**
   * Get node
   */
  async getNode(nodeId: string) {
    return await prisma.interplanetaryNode.findUnique({
      where: { nodeId },
      include: {
        relayGrid: true,
        settlements: true,
        issuances: true,
        cbdcIssuances: true,
      },
    });
  }

  /**
   * List nodes by planetary location
   */
  async listNodes(planetaryLocation?: string) {
    return await prisma.interplanetaryNode.findMany({
      where: planetaryLocation ? { planetaryLocation } : undefined,
      orderBy: { createdAt: 'desc' },
    });
  }

  /**
   * Update node status
   */
  async updateNodeStatus(nodeId: string, status: string): Promise<void> {
    await prisma.interplanetaryNode.update({
      where: { nodeId },
      data: { status },
    });
  }
}

export const ispNodeService = new IspNodeService();

