import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserNotificationEntity } from './entities/user_notifications.entity';

@Injectable()
export class UserNotificationsService {
  constructor(
    @InjectRepository(UserNotificationEntity)
    private readonly userNotificationRepository: Repository<UserNotificationEntity>,
  ) {}

  /**
   * Creates an in-app notification.
   */
  async createNotification(
    userId: number,
    type: string,
    message: string,
  ): Promise<UserNotificationEntity> {
    const notification = new UserNotificationEntity();
    notification.userId = userId;
    notification.type = type;
    notification.message = message;
    notification.isRead = 0;

    return this.userNotificationRepository.save(notification);
  }

  /**
   * Retrieves paginated notifications for a specific user.
   */
  async getUserNotifications(userId: number, page: number = 1, limit: number = 10) {
    const offset = (page - 1) * limit;

    const [notifications, total] = await this.userNotificationRepository.findAndCount({
      where: { userId },
      order: { createdAt: 'DESC' },
      skip: offset,
      take: limit,
    });

    return {
      success: true,
      notifications,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    };
  }

  /**
   * Marks a specific notification as read.
   */
  async markAsRead(notificationId: number, userId: number): Promise<boolean> {
    const notification = await this.userNotificationRepository.findOne({
      where: { id: notificationId, userId },
    });

    if (!notification) {
      return false;
    }

    notification.isRead = 1;
    await this.userNotificationRepository.save(notification);
    return true;
  }

  /**
   * Marks all unread notifications of a user as read.
   */
  async markAllAsRead(userId: number): Promise<boolean> {
    await this.userNotificationRepository.update(
      { userId, isRead: 0 },
      { isRead: 1 },
    );
    return true;
  }

  /**
   * Retrieves the count of unread notifications for a user.
   */
  async getUnreadCount(userId: number): Promise<number> {
    return this.userNotificationRepository.count({
      where: { userId, isRead: 0 },
    });
  }

  /**
   * Deletes a specific notification.
   */
  async deleteNotification(notificationId: number, userId: number): Promise<boolean> {
    const notification = await this.userNotificationRepository.findOne({
      where: { id: notificationId, userId },
    });

    if (!notification) {
      return false;
    }

    await this.userNotificationRepository.remove(notification);
    return true;
  }

  /**
   * Deletes all notifications for a specific user.
   */
  async deleteAllNotifications(userId: number): Promise<boolean> {
    await this.userNotificationRepository.delete({ userId });
    return true;
  }
}
