import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import * as Handlebars from 'handlebars';
import { PrismaService } from '@core/database/prisma/prisma.service';

/**
 * 模板服务
 * 负责管理和渲染通知模板
 */
@Injectable()
export class TemplateService {
  private readonly logger = new Logger(TemplateService.name);

  constructor(private readonly prisma: PrismaService) {
    this.registerHelpers();
  }

  /**
   * 注册 Handlebars 辅助函数
   */
  private registerHelpers() {
    // 日期格式化
    Handlebars.registerHelper('formatDate', (date: Date | string) => {
      if (!date) return '';
      const d = new Date(date);
      return d.toLocaleString('zh-CN');
    });

    // 货币格式化
    Handlebars.registerHelper('formatCurrency', (amount: number) => {
      if (!amount) return '¥0.00';
      return `¥${amount.toFixed(2)}`;
    });

    // 条件判断
    Handlebars.registerHelper('ifEquals', function(arg1, arg2, options: any) {
      return arg1 === arg2 ? options.fn(this) : options.inverse(this);
    });
  }

  /**
   * 渲染模板
   */
  async render(
    templateCode: string,
    variables: Record<string, any>,
  ): Promise<{
    subject: string;
    content: string;
  }> {
    const template = await this.prisma.notificationTemplate.findUnique({
      where: { code: templateCode },
    });

    if (!template) {
      throw new NotFoundException(`Template ${templateCode} not found`);
    }

    if (!template.isActive) {
      throw new Error(`Template ${templateCode} is not active`);
    }

    try {
      const subjectTemplate = Handlebars.compile(template.subject || '');
      const contentTemplate = Handlebars.compile(template.template);

      const subject = subjectTemplate(variables);
      const content = contentTemplate(variables);

      this.logger.debug(`Template ${templateCode} rendered successfully`);

      return { subject, content };
    } catch (error) {
      this.logger.error(`Failed to render template ${templateCode}`, error);
      throw error;
    }
  }

  /**
   * 创建模板
   */
  async create(data: {
    code: string;
    name: string;
    description?: string;
    channel: string;
    subject?: string;
    template: string;
    variables: string[];
    example?: any;
    priority?: string;
  }) {
    return this.prisma.notificationTemplate.create({
      data: data as any,
    });
  }

  /**
   * 更新模板
   */
  async update(code: string, data: any) {
    return this.prisma.notificationTemplate.update({
      where: { code },
      data,
    });
  }

  /**
   * 删除模板（软删除 - 设为不活跃）
   */
  async delete(code: string) {
    return this.prisma.notificationTemplate.update({
      where: { code },
      data: { isActive: false },
    });
  }

  /**
   * 获取所有模板
   */
  async findAll(channel?: string) {
    return this.prisma.notificationTemplate.findMany({
      where: channel ? { channel: channel as any } : undefined,
      orderBy: { createdAt: 'desc' },
    });
  }

  /**
   * 根据代码获取模板
   */
  async findByCode(code: string) {
    const template = await this.prisma.notificationTemplate.findUnique({
      where: { code },
    });

    if (!template) {
      throw new NotFoundException(`Template ${code} not found`);
    }

    return template;
  }

  /**
   * 测试渲染（不保存）
   */
  async testRender(templateCode: string, variables: Record<string, any>) {
    return this.render(templateCode, variables);
  }
}

