import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Notification } from './entities/notification.entity';
import { UserNotification } from './entities/user-notification.entity';

export class NotificationRepository {
  constructor(
    @InjectRepository(Notification)
    private readonly notificationRepository: Repository<Notification>,
    @InjectRepository(UserNotification)
    private readonly userNotificationRepository: Repository<UserNotification>,
  ) {}

  async findAllNotification(take: number, skip: number) {
    const [notification, count] =
      await this.notificationRepository.findAndCount({
        skip,
        take,
        select: ['id', 'content', 'title', 'created_at'],
        order: { created_at: 'DESC' },
      });
    const response = {
      count,
      notification,
    };

    return response;
  }

  async findUserNotification(userId: string, take: number, skip: number) {
    const [UserNotification, count] =
      await this.userNotificationRepository.findAndCount({
        skip,
        take,
        where: {
          app_user_id: userId,
        },
        select: ['id', 'app_user_id', 'title', 'message', 'created_at', 'data'],
        order: {
          created_at: 'DESC',
        },
      });

    const parsedData = UserNotification.map((notification) => {
      return {
        ...notification,
        data: notification.data
          ? JSON.parse(notification.data)
          : notification.data,
      };
    });

    const response = {
      count,
      user_notification: parsedData,
    };

    return response;
  }
}
