// Deployment Rollback Service
// Handles rollback of failed deployments

import { proxmoxVEIntegration } from '@/infrastructure/proxmox/proxmox-ve-integration.service';
import prisma from '@/shared/database/prisma';
import { logger } from '@/infrastructure/monitoring/logger';
import { DbisError, ErrorCode } from '@/shared/types';

export interface RollbackRequest {
  deploymentId: string;
  reason?: string;
}

export interface RollbackResult {
  success: boolean;
  deploymentId: string;
  containersRemoved: string[];
  errors?: string[];
}

export class DeploymentRollbackService {
  /**
   * Rollback a failed deployment
   */
  async rollbackDeployment(request: RollbackRequest): Promise<RollbackResult> {
    const deployment = await prisma.iruDeployment.findUnique({
      where: { deploymentId: request.deploymentId },
      include: {
        subscription: {
          select: {
            subscriptionId: true,
          },
        },
      },
    });

    if (!deployment) {
      throw new DbisError(ErrorCode.NOT_FOUND, `Deployment ${request.deploymentId} not found`);
    }

    const containers = (deployment.containers as Array<{ name: string; vmid?: number }>) || [];
    const containersRemoved: string[] = [];
    const errors: string[] = [];

    // Remove containers
    for (const container of containers) {
      if (container.vmid) {
        try {
          // Stop container
          await proxmoxVEIntegration.stopContainer(container.vmid);
          
          // Delete container
          await proxmoxVEIntegration.deleteContainer(container.vmid);
          
          containersRemoved.push(container.name || `vmid-${container.vmid}`);
          
          logger.info('Container removed during rollback', {
            deploymentId: request.deploymentId,
            containerName: container.name,
            vmid: container.vmid,
          });
        } catch (error) {
          errors.push(`Failed to remove container ${container.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
          logger.error('Failed to remove container during rollback', {
            deploymentId: request.deploymentId,
            containerName: container.name,
            error: error instanceof Error ? error.message : 'Unknown error',
          });
        }
      }
    }

    // Update deployment status
    await prisma.iruDeployment.update({
      where: { deploymentId: request.deploymentId },
      data: {
        status: 'cancelled',
        metadata: {
          ...((deployment.metadata as Record<string, unknown>) || {}),
          rollbackReason: request.reason || 'Deployment failed',
          rollbackAt: new Date(),
          containersRemoved,
        },
        updatedAt: new Date(),
      },
    });

    logger.info('Deployment rollback completed', {
      deploymentId: request.deploymentId,
      containersRemoved: containersRemoved.length,
      errors: errors.length,
    });

    return {
      success: errors.length === 0,
      deploymentId: request.deploymentId,
      containersRemoved,
      errors: errors.length > 0 ? errors : undefined,
    };
  }
}

export const deploymentRollbackService = new DeploymentRollbackService();
