// IRU Portal Service
// Business logic for Phoenix Portal

import prisma from '@/shared/database/prisma';
import { DbisError, ErrorCode } from '@/shared/types';

export interface PortalDashboard {
  subscription: {
    subscriptionId: string;
    offering: {
      name: string;
      capacityTier: number;
    };
    subscriptionStatus: string;
    activationDate: Date | null;
    latestAgreement: {
      agreementId: string;
      status: string;
    } | null;
  } | null;
  deploymentStatus: {
    status: string;
    deployedAt: Date | null;
  };
  serviceHealth: {
    overall: string;
    services: Array<{ serviceName: string; status: string }>;
  };
  recentActivity: Array<{
    notificationId: string;
    template: string;
    subject: string | null;
    status: string;
    createdAt: Date;
  }>;
}

export class PortalService {
  /**
   * Get participant dashboard data
   */
  async getDashboard(participantId: string): Promise<PortalDashboard> {
    const subscription = await prisma.iruSubscription.findFirst({
      where: {
        participantId,
        subscriptionStatus: 'active',
      },
      include: {
        offering: true,
        agreements: {
          orderBy: {
            createdAt: 'desc',
          },
          take: 1,
        },
      },
    });

    // Get deployment status from deployment service
    const { deploymentOrchestrator } = await import('@/core/iru/deployment/deployment-orchestrator.service');
    const { monitoringService } = await import('@/core/iru/monitoring.service');
    
    let deploymentStatus = {
      status: subscription ? 'deployed' : 'not_deployed',
      deployedAt: subscription?.activationDate,
    };

    if (subscription) {
      try {
        const deployments = await prisma.iruDeployment.findMany({
          where: {
            subscriptionId: subscription.id,
          },
          orderBy: {
            completedAt: 'desc',
          },
          take: 1,
        });

        if (deployments.length > 0) {
          const latestDeployment = await deploymentOrchestrator.getDeploymentStatus(deployments[0].deploymentId);
          deploymentStatus = {
            status: latestDeployment.status,
            deployedAt: latestDeployment.stages.find((s) => s.status === 'completed')?.completedAt || subscription.activationDate,
          };
        }
      } catch (error) {
        // Fallback to basic status
      }
    }

    // Get service health from monitoring service
    let serviceHealth = {
      overall: 'healthy' as const,
      services: [] as Array<{ serviceName: string; status: string }>,
    };

    if (subscription) {
      try {
        const health = await monitoringService.getServiceHealth(subscription.subscriptionId);
        serviceHealth = {
          overall: health.overall,
          services: health.services.map((s) => ({
            serviceName: s.serviceName,
            status: s.status,
          })),
        };
      } catch (error) {
        // Fallback to basic health
      }
    }

    // Get recent activity
    const recentActivity = await prisma.iruNotification.findMany({
      where: {
        recipientId: participantId,
        recipientType: 'portal',
      },
      orderBy: {
        createdAt: 'desc',
      },
      take: 10,
      select: {
        notificationId: true,
        template: true,
        subject: true,
        status: true,
        createdAt: true,
      },
    });

    return {
      subscription: subscription
        ? {
            subscriptionId: subscription.subscriptionId,
            offering: {
              name: subscription.offering.name,
              capacityTier: subscription.offering.capacityTier,
            },
            subscriptionStatus: subscription.subscriptionStatus,
            activationDate: subscription.activationDate,
            latestAgreement: subscription.agreements[0]
              ? {
                  agreementId: subscription.agreements[0].agreementId,
                  status: subscription.agreements[0].status,
                }
              : null,
          }
        : null,
      deploymentStatus,
      serviceHealth,
      recentActivity,
    };
  }

  /**
   * Get IRU management data
   */
  async getIRUManagement(participantId: string): Promise<Array<{
    subscriptionId: string;
    offering: {
      name: string;
      capacityTier: number;
    };
    subscriptionStatus: string;
    subscriptionDate: Date;
    activationDate: Date | null;
    terminationDate: Date | null;
    agreements: Array<{
      agreementId: string;
      status: string;
      executedAt: Date | null;
    }>;
  }>> {
    const subscriptions = await prisma.iruSubscription.findMany({
      where: {
        participantId,
      },
      include: {
        offering: true,
        agreements: {
          orderBy: {
            createdAt: 'desc',
          },
        },
      },
      orderBy: {
        subscriptionDate: 'desc',
      },
    });

    return subscriptions.map((sub) => ({
      subscriptionId: sub.subscriptionId,
      offering: {
        name: sub.offering.name,
        capacityTier: sub.offering.capacityTier,
      },
      subscriptionStatus: sub.subscriptionStatus,
      subscriptionDate: sub.subscriptionDate,
      activationDate: sub.activationDate,
      terminationDate: sub.terminationDate,
      agreements: sub.agreements.map((agreement) => ({
        agreementId: agreement.agreementId,
        status: agreement.status,
        executedAt: agreement.executedAt,
      })),
    }));
  }

  /**
   * Get deployment status
   */
  async getDeploymentStatus(subscriptionId: string): Promise<any> {
    const subscription = await prisma.iruSubscription.findUnique({
      where: { subscriptionId },
    });

    if (!subscription) {
      throw new DbisError(ErrorCode.NOT_FOUND, `Subscription ${subscriptionId} not found`);
    }

    // Integrate with deployment orchestrator
    const { deploymentOrchestrator } = await import('@/core/iru/deployment/deployment-orchestrator.service');
    const { monitoringService } = await import('@/core/iru/monitoring.service');
    
    const deployments = await prisma.iruDeployment.findMany({
      where: {
        subscriptionId: subscription.id,
      },
      orderBy: {
        completedAt: 'desc',
      },
      take: 1,
    });

    let deploymentData = {
      subscriptionId: subscription.subscriptionId,
      status: subscription.subscriptionStatus === 'active' ? 'deployed' : 'pending',
      deployedAt: subscription.activationDate,
      containers: [] as Array<{ name: string; status: string; ip?: string }>,
      network: {} as Record<string, unknown>,
      health: 'unknown' as string,
    };

    if (deployments.length > 0) {
      try {
        const deploymentStatus = await deploymentOrchestrator.getDeploymentStatus(deployments[0].deploymentId);
        const health = await monitoringService.getServiceHealth(subscription.subscriptionId);
        
        deploymentData = {
          subscriptionId: subscription.subscriptionId,
          status: deploymentStatus.status,
          deployedAt: deploymentStatus.stages.find((s) => s.status === 'completed')?.completedAt || subscription.activationDate,
          containers: deploymentStatus.containers,
          network: {},
          health: health.overall,
        };
      } catch (error) {
        // Fallback to basic status
      }
    }

    return deploymentData;
  }
}

export const portalService = new PortalService();
