import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Notification, NotificationType } from './notification.entity';
import { NotificationsGateway } from './notifications.gateway';
import { ModuleRef } from '@nestjs/core';
import { MailService } from './mail.service';
import { UsersService } from 'src/users/users.service';

@Injectable()
export class NotificationsService {
  private notificationsGateway: NotificationsGateway;

  constructor(
    @InjectRepository(Notification)
    private notificationRepository: Repository<Notification>,
    private mailService: MailService,
    @Inject(forwardRef(() => UsersService))
    private usersService: UsersService,
    private moduleRef: ModuleRef, // only ModuleRef, no direct gateway injection
  ) {}

  onModuleInit() {
    // Lazy load the gateway after module init
    this.notificationsGateway = this.moduleRef.get(NotificationsGateway, {
      strict: false,
    });
  }

  async createNotification(data: {
    userId: number;
    title: string;
    message: string;
    type: NotificationType;
  }) {
    const notification = this.notificationRepository.create(data);
    const saved = await this.notificationRepository.save(notification);

    // WebSocket
    // this.notificationsGateway.sendNotificationToUser(data.userId, saved);

    // Email
    const user = await this.usersService.findOne(data.userId);

    if (user?.email) {
      await this.mailService.sendMail(
        user.email,
        data.title,
        this.buildEmailTemplate(data.title, data.message),
      );
    }

    return saved;
  }

  async getUserNotifications(userId: number, unreadOnly: boolean = false) {
    const where: any = { userId };
    if (unreadOnly) where.isRead = false;
    return this.notificationRepository.find({
      where,
      order: { createdAt: 'DESC' },
    });
  }

  async markAsRead(notificationId: number, userId: number) {
    const notification = await this.notificationRepository.findOne({
      where: { id: notificationId, userId },
    });
    if (notification) {
      notification.isRead = true;
      await this.notificationRepository.save(notification);
    }
    return notification;
  }

  private buildEmailTemplate(title: string, message: string) {
    return `
    <div style="font-family: Arial; padding:20px;">
      <h2 style="color:#4F46E5;">${title}</h2>
      <p style="font-size:14px; color:#444;">
        ${message}
      </p>

      <div style="margin-top:20px;">
        <a href="http://localhost:3000"
          style="
            background:#4F46E5;
            color:#fff;
            padding:10px 16px;
            text-decoration:none;
            border-radius:6px;
          ">
          Open Dashboard
        </a>
      </div>

      <p style="margin-top:20px; font-size:12px; color:#999;">
        HR System Notification
      </p>
    </div>
  `;
  }
}
