// Template Loader Service
// Loads notification templates from database or filesystem

import prisma from '@/shared/database/prisma';
import fs from 'fs/promises';
import path from 'path';
import { logger } from '@/infrastructure/monitoring/logger';

export interface Template {
  id: string;
  name: string;
  subject: string;
  body: string;
  variables: string[]; // List of required variables
}

export class TemplateLoaderService {
  /**
   * Load template from database or filesystem
   */
  async loadTemplate(templateName: string): Promise<Template> {
    // Try database first
    try {
      const dbTemplate = await prisma.iruNotificationTemplate.findUnique({
        where: { templateName },
      });

      if (dbTemplate) {
        return {
          id: dbTemplate.id,
          name: dbTemplate.templateName,
          subject: dbTemplate.subject,
          body: dbTemplate.body,
          variables: (dbTemplate.requiredVariables as string[]) || [],
        };
      }
    } catch (error) {
      logger.warn('Failed to load template from database', {
        templateName,
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }

    // Fallback to filesystem
    try {
      const templatePath = path.join(
        process.cwd(),
        'templates',
        'notifications',
        `${templateName}.json`
      );
      const templateContent = await fs.readFile(templatePath, 'utf-8');
      const template = JSON.parse(templateContent);

      return {
        id: templateName,
        name: templateName,
        subject: template.subject,
        body: template.body,
        variables: template.variables || [],
      };
    } catch (error) {
      logger.warn('Failed to load template from filesystem', {
        templateName,
        error: error instanceof Error ? error.message : 'Unknown error',
      });
    }

    // Fallback to hardcoded templates
    return this.getDefaultTemplate(templateName);
  }

  /**
   * Get default template (fallback)
   */
  private getDefaultTemplate(templateName: string): Template {
    const templates: Record<string, Template> = {
      'inquiry-submitted': {
        id: 'inquiry-submitted',
        name: 'inquiry-submitted',
        subject: 'IRU Inquiry Submitted',
        body: 'Your IRU inquiry has been submitted successfully. Inquiry ID: {{inquiryId}}',
        variables: ['inquiryId'],
      },
      'inquiry-acknowledged': {
        id: 'inquiry-acknowledged',
        name: 'inquiry-acknowledged',
        subject: 'IRU Inquiry Acknowledged',
        body: 'Your IRU inquiry has been acknowledged. We will review it within 24 hours. Inquiry ID: {{inquiryId}}',
        variables: ['inquiryId'],
      },
      'qualification-complete': {
        id: 'qualification-complete',
        name: 'qualification-complete',
        subject: 'IRU Qualification Complete',
        body: 'Your IRU qualification is complete. Status: {{status}}. Inquiry ID: {{inquiryId}}',
        variables: ['status', 'inquiryId'],
      },
      'agreement-ready': {
        id: 'agreement-ready',
        name: 'agreement-ready',
        subject: 'IRU Agreement Ready for Signature',
        body: 'Your IRU Participation Agreement is ready for signature. Agreement ID: {{agreementId}}',
        variables: ['agreementId'],
      },
      'deployment-complete': {
        id: 'deployment-complete',
        name: 'deployment-complete',
        subject: 'IRU Deployment Complete',
        body: 'Your IRU infrastructure has been deployed successfully. Subscription ID: {{subscriptionId}}',
        variables: ['subscriptionId'],
      },
      'deployment-failed': {
        id: 'deployment-failed',
        name: 'deployment-failed',
        subject: 'IRU Deployment Failed',
        body: 'Your IRU deployment has failed. Deployment ID: {{deploymentId}}. Error: {{error}}',
        variables: ['deploymentId', 'error'],
      },
      'payment-success': {
        id: 'payment-success',
        name: 'payment-success',
        subject: 'Payment Successful',
        body: 'Your payment for IRU subscription {{subscriptionId}} has been processed successfully. Amount: {{currency}} {{amount}}',
        variables: ['subscriptionId', 'currency', 'amount'],
      },
      'payment-failed': {
        id: 'payment-failed',
        name: 'payment-failed',
        subject: 'Payment Failed',
        body: 'Your payment for IRU subscription {{subscriptionId}} has failed. Transaction ID: {{transactionId}}',
        variables: ['subscriptionId', 'transactionId'],
      },
    };

    return (
      templates[templateName] || {
        id: templateName,
        name: templateName,
        subject: 'DBIS IRU Notification',
        body: 'You have a new notification from DBIS IRU.',
        variables: [],
      }
    );
  }
}

export const templateLoaderService = new TemplateLoaderService();
