// DBIS Temporal Liquidity Portal Service
// Portal creation and management

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { Decimal } from '@prisma/client/runtime/library';


export interface CreatePortalRequest {
  portalName: string;
  targetTimeDelta: number; // Δ in seconds
  confidenceLevel: number; // 0-1
  maxLiquidityBorrow: number;
}

export class TlpPortalService {
  /**
   * Create temporal liquidity portal
   */
  async createPortal(request: CreatePortalRequest) {
    if (request.confidenceLevel < 0 || request.confidenceLevel > 1) {
      throw new Error('Confidence level must be between 0 and 1');
    }

    const portalId = `TLP-${uuidv4()}`;

    const portal = await prisma.temporal_liquidity_portals.create({
      data: {
        portalId,
        portalName: request.portalName,
        targetTimeDelta: request.targetTimeDelta,
        confidenceLevel: new Decimal(request.confidenceLevel),
        maxLiquidityBorrow: new Decimal(request.maxLiquidityBorrow),
        status: 'active',
      },
    });

    return portal;
  }

  /**
   * Get portal by ID
   */
  async getPortal(portalId: string) {
    return await prisma.temporal_liquidity_portals.findUnique({
      where: { portalId },
      include: {
        reserves: {
          where: { status: 'available' },
          orderBy: { predictedTime: 'asc' },
        },
        buffers: true,
      },
    });
  }

  /**
   * Get all active portals
   */
  async getActivePortals() {
    return await prisma.temporal_liquidity_portals.findMany({
      where: { status: 'active' },
      include: {
        reserves: {
          where: { status: 'available' },
        },
        buffers: true,
      },
    });
  }

  /**
   * Suspend portal
   */
  async suspendPortal(portalId: string) {
    return await prisma.temporal_liquidity_portals.update({
      where: { portalId },
      data: { status: 'suspended' },
    });
  }

  /**
   * Close portal
   */
  async closePortal(portalId: string) {
    return await prisma.temporal_liquidity_portals.update({
      where: { portalId },
      data: { status: 'closed' },
    });
  }

  /**
   * Update portal configuration
   */
  async updatePortal(
    portalId: string,
    updates: {
      confidenceLevel?: number;
      maxLiquidityBorrow?: number;
      targetTimeDelta?: number;
    }
  ) {
    const data: Record<string, unknown> = {};

    if (updates.confidenceLevel !== undefined) {
      if (updates.confidenceLevel < 0 || updates.confidenceLevel > 1) {
        throw new Error('Confidence level must be between 0 and 1');
      }
      data.confidenceLevel = new Decimal(updates.confidenceLevel);
    }

    if (updates.maxLiquidityBorrow !== undefined) {
      data.maxLiquidityBorrow = new Decimal(updates.maxLiquidityBorrow);
    }

    if (updates.targetTimeDelta !== undefined) {
      data.targetTimeDelta = updates.targetTimeDelta;
    }

    return await prisma.temporal_liquidity_portals.update({
      where: { portalId },
      data,
    });
  }
}

export const tlpPortalService = new TlpPortalService();

