// IRU Inquiry Service
// Processing and management of IRU inquiries

import prisma from '@/shared/database/prisma';
import { DbisError, ErrorCode } from '@/shared/types';
import { PreliminaryInfo, QualificationResult, UpdateInquiryData } from './types/common.types';

export interface UpdateInquiryRequest {
  status?: string;
  preliminaryInfo?: PreliminaryInfo;
  qualificationResult?: QualificationResult;
  capacityTier?: number;
  riskScore?: number;
  notes?: string;
}

export class InquiryService {
  /**
   * Acknowledge inquiry
   */
  async acknowledgeInquiry(inquiryId: string): Promise<any> {
    const inquiry = await prisma.iruInquiry.findUnique({
      where: { inquiryId },
    });

    if (!inquiry) {
      throw new DbisError(ErrorCode.NOT_FOUND, `Inquiry ${inquiryId} not found`);
    }

    if (inquiry.status !== 'submitted') {
      throw new DbisError(
        ErrorCode.VALIDATION_ERROR,
        `Inquiry ${inquiryId} is not in submitted status`
      );
    }

    const updated = await prisma.iruInquiry.update({
      where: { inquiryId },
      data: {
        status: 'acknowledged',
        acknowledgedAt: new Date(),
        updatedAt: new Date(),
      },
    });

    // Send acknowledgment email to participant
    try {
      const { notificationService } = await import('@/core/iru/notifications/notification.service');
      await notificationService.sendNotification({
        recipient: inquiry.contactEmail,
        recipientType: 'email',
        template: 'inquiry-acknowledged',
        variables: {
          inquiryId: inquiry.inquiryId,
          organizationName: inquiry.organizationName,
        },
      });
    } catch (error) {
      const { logger } = await import('@/infrastructure/monitoring/logger');
      logger.warn('Failed to send acknowledgment email', {
        inquiryId: inquiry.inquiryId,
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }

    return {
      inquiryId: updated.inquiryId,
      status: updated.status,
      acknowledgedAt: updated.acknowledgedAt,
    };
  }

  /**
   * Update inquiry status and information
   */
  async updateInquiry(inquiryId: string, request: UpdateInquiryRequest): Promise<any> {
    const inquiry = await prisma.iruInquiry.findUnique({
      where: { inquiryId },
    });

    if (!inquiry) {
      throw new DbisError(ErrorCode.NOT_FOUND, `Inquiry ${inquiryId} not found`);
    }

    const updateData: Partial<UpdateInquiryData> = {
      updatedAt: new Date(),
    };

    if (request.status) {
      updateData.status = request.status;
      if (request.status === 'in_review' && !inquiry.reviewedAt) {
        updateData.reviewedAt = new Date();
      }
      if (request.status === 'qualified' || request.status === 'rejected') {
        updateData.completedAt = new Date();
      }
    }

    if (request.preliminaryInfo !== undefined) {
      updateData.preliminaryInfo = request.preliminaryInfo;
    }

    if (request.qualificationResult !== undefined) {
      updateData.qualificationResult = request.qualificationResult;
    }

    if (request.capacityTier !== undefined) {
      updateData.capacityTier = request.capacityTier;
    }

    if (request.riskScore !== undefined) {
      updateData.riskScore = request.riskScore;
    }

    if (request.notes !== undefined) {
      updateData.notes = request.notes;
    }

    const updated = await prisma.iruInquiry.update({
      where: { inquiryId },
      data: updateData,
    });

    return {
      inquiryId: updated.inquiryId,
      status: updated.status,
      preliminaryInfo: updated.preliminaryInfo,
      qualificationResult: updated.qualificationResult,
      capacityTier: updated.capacityTier,
      riskScore: updated.riskScore ? Number(updated.riskScore) : undefined,
      notes: updated.notes,
      reviewedAt: updated.reviewedAt,
      completedAt: updated.completedAt,
    };
  }

  /**
   * Get all inquiries with filters
   */
  async getInquiries(filters?: {
    status?: string;
    offeringId?: string;
    capacityTier?: number;
    limit?: number;
    offset?: number;
  }): Promise<Array<{ inquiryId: string; status: string; contactEmail: string; organizationName: string; [key: string]: unknown }>> {
    const where: Record<string, unknown> = {};

    if (filters?.status) {
      where.status = filters.status;
    }

    if (filters?.offeringId) {
      const offering = await prisma.iruOffering.findUnique({
        where: { offeringId: filters.offeringId },
      });
      if (offering) {
        where.offeringId = offering.id;
      }
    }

    if (filters?.capacityTier) {
      where.capacityTier = filters.capacityTier;
    }

    const inquiries = await prisma.iruInquiry.findMany({
      where,
      include: {
        offering: {
          select: {
            offeringId: true,
            name: true,
            capacityTier: true,
          },
        },
      },
      orderBy: {
        submittedAt: 'desc',
      },
      take: filters?.limit || 100,
      skip: filters?.offset || 0,
    });

    return inquiries.map((inquiry) => ({
      inquiryId: inquiry.inquiryId,
      organizationName: inquiry.organizationName,
      institutionalType: inquiry.institutionalType,
      jurisdiction: inquiry.jurisdiction,
      contactEmail: inquiry.contactEmail,
      contactName: inquiry.contactName,
      status: inquiry.status,
      offering: inquiry.offering,
      capacityTier: inquiry.capacityTier,
      riskScore: inquiry.riskScore ? Number(inquiry.riskScore) : undefined,
      submittedAt: inquiry.submittedAt,
      acknowledgedAt: inquiry.acknowledgedAt,
      reviewedAt: inquiry.reviewedAt,
      completedAt: inquiry.completedAt,
    }));
  }

  /**
   * Get inquiry by ID with full details
   */
  async getInquiryById(inquiryId: string): Promise<any> {
    const inquiry = await prisma.iruInquiry.findUnique({
      where: { inquiryId },
      include: {
        offering: true,
        subscription: {
          include: {
            agreements: {
              orderBy: {
                createdAt: 'desc',
              },
              take: 1,
            },
          },
        },
      },
    });

    if (!inquiry) {
      throw new DbisError(ErrorCode.NOT_FOUND, `Inquiry ${inquiryId} not found`);
    }

    return {
      inquiryId: inquiry.inquiryId,
      organizationName: inquiry.organizationName,
      institutionalType: inquiry.institutionalType,
      jurisdiction: inquiry.jurisdiction,
      contactEmail: inquiry.contactEmail,
      contactPhone: inquiry.contactPhone,
      contactName: inquiry.contactName,
      estimatedVolume: inquiry.estimatedVolume,
      expectedGoLive: inquiry.expectedGoLive,
      status: inquiry.status,
      preliminaryInfo: inquiry.preliminaryInfo,
      qualificationResult: inquiry.qualificationResult,
      capacityTier: inquiry.capacityTier,
      riskScore: inquiry.riskScore ? Number(inquiry.riskScore) : undefined,
      notes: inquiry.notes,
      offering: {
        offeringId: inquiry.offering.offeringId,
        name: inquiry.offering.name,
        capacityTier: inquiry.offering.capacityTier,
        institutionalType: inquiry.offering.institutionalType,
      },
      subscription: inquiry.subscription
        ? {
            subscriptionId: inquiry.subscription.subscriptionId,
            subscriptionStatus: inquiry.subscription.subscriptionStatus,
            activationDate: inquiry.subscription.activationDate,
            latestAgreement: inquiry.subscription.agreements[0]
              ? {
                  agreementId: inquiry.subscription.agreements[0].agreementId,
                  status: inquiry.subscription.agreements[0].status,
                }
              : null,
          }
        : null,
      submittedAt: inquiry.submittedAt,
      acknowledgedAt: inquiry.acknowledgedAt,
      reviewedAt: inquiry.reviewedAt,
      completedAt: inquiry.completedAt,
    };
  }
}

export const inquiryService = new InquiryService();
