import * as notificationsRepo from '../repositories/notifications.repository';
import { pool } from '../config/database';

export const notifyStaff = async (type: string, title: string, message: string, includeAgents = false, connection?: any) => {
  const db = connection || pool;
  // Roles: 1 = SUPER_ADMIN, 2 = ADMIN, 3 = AGENT
  const roles = includeAgents ? [1, 2, 3] : [1, 2];
  
  const [users] = await (db as any).query(`SELECT id FROM users WHERE role_id IN (?) AND status != 'BANNED'`, [roles]);
  const userIds = (users as any[]).map(u => u.id);
  
  if (userIds.length === 0) return;

  for (const userId of userIds) {
    await notificationsRepo.create({
      user_id: userId,
      type,
      title,
      message
    }, db);
  }
};

export const getUserNotifications = async (userId: number) => {
  return notificationsRepo.findByUser(userId);
};

export const getUnreadCount = async (userId: number) => {
  return notificationsRepo.countUnread(userId);
};

export const createNotification = async (data: any) => {
  return notificationsRepo.create(data);
};

export const markAsRead = async (id: number, userId: number) => {
  await notificationsRepo.markAsRead(id, userId);
};

export const markAllAsRead = async (userId: number) => {
  await notificationsRepo.markAllAsRead(userId);
};

export const deleteNotification = async (notificationId: number, userId: number) => {
  const notification = await notificationsRepo.findById(notificationId);
  if (!notification || notification.user_id !== userId) {
    throw new Error('Notification introuvable ou accès refusé');
  }
  await notificationsRepo.remove(notificationId);
};
