// 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: 'SolaceNet (IRU) inquiry submitted — Solace Bank Group PLC',
        body:
          'Your SolaceNet (Irrevocable Right of Use) inquiry has been submitted. Vendor: Solace Bank Group PLC. Inquiry ID: {{inquiryId}}',
        variables: ['inquiryId'],
      },
      'inquiry-acknowledged': {
        id: 'inquiry-acknowledged',
        name: 'inquiry-acknowledged',
        subject: 'SolaceNet inquiry acknowledged — Solace Bank Group PLC',
        body:
          'Your SolaceNet (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: 'SolaceNet qualification complete — Solace Bank Group PLC',
        body:
          'Your SolaceNet (IRU) qualification is complete. Status: {{status}}. Inquiry ID: {{inquiryId}}',
        variables: ['status', 'inquiryId'],
      },
      'agreement-ready': {
        id: 'agreement-ready',
        name: 'agreement-ready',
        subject: 'SolaceNet agreement ready for signature',
        body:
          'Your SolaceNet participation agreement is ready for signature. Agreement ID: {{agreementId}}',
        variables: ['agreementId'],
      },
      'deployment-complete': {
        id: 'deployment-complete',
        name: 'deployment-complete',
        subject: 'SolaceNet deployment complete',
        body:
          'Your SolaceNet (IRU) infrastructure has been deployed successfully. Subscription ID: {{subscriptionId}}',
        variables: ['subscriptionId'],
      },
      'deployment-failed': {
        id: 'deployment-failed',
        name: 'deployment-failed',
        subject: 'SolaceNet deployment failed',
        body:
          'Your SolaceNet (IRU) deployment has failed. Deployment ID: {{deploymentId}}. Error: {{error}}',
        variables: ['deploymentId', 'error'],
      },
      'payment-success': {
        id: 'payment-success',
        name: 'payment-success',
        subject: 'Payment successful — SolaceNet',
        body:
          'Your payment for SolaceNet subscription {{subscriptionId}} has been processed successfully. Amount: {{currency}} {{amount}}',
        variables: ['subscriptionId', 'currency', 'amount'],
      },
      'payment-failed': {
        id: 'payment-failed',
        name: 'payment-failed',
        subject: 'Payment failed — SolaceNet',
        body:
          'Your payment for SolaceNet subscription {{subscriptionId}} has failed. Transaction ID: {{transactionId}}',
        variables: ['subscriptionId', 'transactionId'],
      },
    };

    return (
      templates[templateName] || {
        id: templateName,
        name: templateName,
        subject: 'SolaceNet / Sankofa Marketplace notification',
        body: 'You have a new notification regarding SolaceNet (IRU) on Sankofa Marketplace.',
        variables: [],
      }
    );
  }
}

export const templateLoaderService = new TemplateLoaderService();
