import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import * as Handlebars from 'handlebars';
import * as fs from 'fs/promises';
import * as path from 'path';

@Injectable()
export class NcEmailTemplateService implements OnModuleInit {
  private readonly logger = new Logger(NcEmailTemplateService.name);

  private tplClient: HandlebarsTemplateDelegate | null = null;
  private tplAuditor: HandlebarsTemplateDelegate | null = null;
  private tplAdmin: HandlebarsTemplateDelegate | null = null;
  private tplClosure: HandlebarsTemplateDelegate | null = null;

  async onModuleInit(): Promise<void> {
    const dir = path.join(__dirname, 'email-templates');

    const [header, footer, client, auditor, admin, closure] =
      await Promise.all([
        fs.readFile(path.join(dir, '_header.partial.html'), 'utf8'),
        fs.readFile(path.join(dir, '_footer.partial.html'), 'utf8'),
        fs.readFile(path.join(dir, 'nc-raised-client.template.html'), 'utf8'),
        fs.readFile(path.join(dir, 'nc-raised-auditor.template.html'), 'utf8'),
        fs.readFile(path.join(dir, 'nc-raised-admin.template.html'), 'utf8'),
        fs.readFile(path.join(dir, 'nc-final-closure.template.html'), 'utf8'),
      ]);

    Handlebars.registerPartial('nc-email-header', header);
    Handlebars.registerPartial('nc-email-footer', footer);

    this.tplClient = Handlebars.compile(client);
    this.tplAuditor = Handlebars.compile(auditor);
    this.tplAdmin = Handlebars.compile(admin);
    this.tplClosure = Handlebars.compile(closure);

    this.logger.log('[NC-EMAIL-TPL] Templates compiled');
  }

  private year(): number {
    return new Date().getFullYear();
  }

  renderNcRaisedClient(ctx: {
    company_name: string;
    audit_type: string;
    audit_date: string;
    auditor_name: string;
    evidence_email: string;
    entries: Array<{
      index: number;
      nc_type: string;
      ncr_statement_html: string;
      criteria_clause_html: string;
      corrective_action: string;
    }>;
  }): string {
    if (!this.tplClient) throw new Error('Client template not compiled');
    return this.tplClient({ ...ctx, year: this.year() });
  }

  renderNcRaisedAuditor(ctx: {
    nc_id: number;
    company_name: string;
    audit_type: string;
    audit_date: string;
    auditor_name: string;
    findings_count: number;
    entries?: Array<{                          // 🆕
      index: number;
      nc_type: string;
      ncr_statement_html: string;
      criteria_clause_html: string;
      corrective_action: string;
    }>;
  }): string {
    if (!this.tplAuditor) throw new Error('Auditor template not compiled');
    return this.tplAuditor({ ...ctx, year: this.year() });
  }

  renderNcRaisedAdmin(ctx: {
    nc_id: number;
    company_name: string;
    audit_type: string;
    audit_date: string;
    auditor_name: string;
    findings_count: number;
    raised_at?: string;
    nc_link?: string;
    evidence_email?: string;   // 🆕
    entries?: Array<{                          // 🆕
      index: number;
      nc_type: string;
      ncr_statement_html: string;
      criteria_clause_html: string;
      corrective_action: string;
    }>;
  }): string {
    if (!this.tplAdmin) throw new Error('Admin template not compiled');
    return this.tplAdmin({ ...ctx, year: this.year() });
  }

  renderFinalClosure(ctx: {
    company_name: string;
    nc_id: number;
    closure_date: string;
    sender_name: string;
  }): string {
    if (!this.tplClosure) throw new Error('Closure template not compiled');
    return this.tplClosure({ ...ctx, year: this.year() });
  }
}
