import { Log } from '@/entities/log.entity';
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SendLogDto } from './dtos/send-log.dto';
import { ZulipService } from './zulip.service';
import AppResponse from '@/system/filters/response/app-response';
import { SystemLang } from '@/system/lang/system.lang';
import { MailerService } from '../mailer/mailer.service';
@Injectable()
export class LogsService {
  constructor(
    @InjectRepository(Log)
    readonly repo: Repository<Log>,
    private readonly zulipService: ZulipService,
    private readonly malerService: MailerService,
  ) {}

  async saveLog(data: SendLogDto) {
    const result = await this.repo.save({
      message: data.message,
      type: data.type,
    });

    if (!result)
      throw new BadRequestException(
        AppResponse.toResponse(null, {
          message: SystemLang.getText('messages', 'error'),
        }),
      );

    // 2. Build nội dung email
    const subject = `[${result.type.toUpperCase()}] - New Log Message`;
    const content = `
      <h3>Log Notification</h3>
      <p><b>Type:</b> ${result.type.toUpperCase()}</p>
      <p><b>Message:</b> ${result.message}</p>
      <p><b>Created At:</b> ${new Date().toLocaleString()}</p>
    `;

    // 3. Gửi email
    await this.malerService.sendMail(subject, content);

    return AppResponse.toResponse(result);
  }
}
