import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Notification, NotificationType } from './entities/notification.entity';
import { User } from '../users/entities/user.entity';

@Injectable()
export class NotificationsService {
  constructor(
    @InjectRepository(Notification)
    private readonly notificationRepo: Repository<Notification>,
  ) {}

  // ─── Lister les notifications d'un utilisateur ───────────────────────────────
  async findAll(userId: number): Promise<{
    notifications: Notification[];
    unread_count: number;
  }> {
    const notifications = await this.notificationRepo.find({
      where: { user: { id: userId } },
      order: { created_at: 'DESC' },
      take: 50,
    });

    const unread_count = notifications.filter(n => !n.is_read).length;

    return { notifications, unread_count };
  }

  // ─── Marquer une notification comme lue ─────────────────────────────────────
  async markAsRead(id: number, userId: number): Promise<Notification | null> {
    const notification = await this.notificationRepo.findOne({
      where: { id, user: { id: userId } },
    });

    if (!notification) return null;

    notification.is_read = true;
    return this.notificationRepo.save(notification);
  }

  // ─── Marquer toutes comme lues ───────────────────────────────────────────────
  async markAllAsRead(userId: number): Promise<{ updated: number }> {
    const result = await this.notificationRepo.update(
      { user: { id: userId }, is_read: false },
      { is_read: true },
    );

    return { updated: result.affected ?? 0 };
  }

  // ─── Créer une notification ──────────────────────────────────────────────────
  async create(
    user: User,
    type: NotificationType,
    message: string,
    link?: string,
  ): Promise<Notification> {
    const notification = this.notificationRepo.create({
      user, type, message, link,
    });
    return this.notificationRepo.save(notification);
  }

  // ─── Supprimer une notification ──────────────────────────────────────────────
  async remove(id: number, userId: number): Promise<{ message: string }> {
    await this.notificationRepo.delete({
      id: +id,
      user: { id: userId },
    });
    return { message: 'Notification supprimée' };
  }

  // ─── Supprimer toutes les notifications lues ─────────────────────────────────
  async removeAllRead(userId: number): Promise<{ deleted: number }> {
    const result = await this.notificationRepo.delete({
      user: { id: userId },
      is_read: true,
    });
    return { deleted: result.affected ?? 0 };
  }

  // ─── Compter les non lues ────────────────────────────────────────────────────
  async countUnread(userId: number): Promise<{ count: number }> {
    const count = await this.notificationRepo.count({
      where: { user: { id: userId }, is_read: false },
    });
    return { count };
  }
}