package ru.soune.nocopy.service.notification;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.soune.nocopy.entity.notification.Notification;
import ru.soune.nocopy.entity.notification.NotificationStatus;
import ru.soune.nocopy.entity.notification.NotificationType;
import ru.soune.nocopy.entity.user.User;
import ru.soune.nocopy.repository.NotificationRepository;
import ru.soune.nocopy.repository.UserRepository;
import ru.soune.nocopy.service.user.UserService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Locale;

@Service
@Slf4j
@RequiredArgsConstructor
public class NotificationService {

    private final NotificationRepository notificationRepository;

    private final UserRepository userRepository;

    private final MessageSource messageSource;

    @Transactional
    public void addNotification(NotificationType notificationType, long userId, Object... args) {
        Notification notification = Notification.builder()
                .notificationType(notificationType)
                .createdAt(LocalDateTime.now())
                .user(userRepository.findById(userId).orElseThrow())
                .status(NotificationStatus.NEW)
                .message(notificationType.getMessageKey())
                .build();

        notificationRepository.save(notification);
    }

    @Transactional
    public void deleteNotification(Notification notification) {
        notificationRepository.delete(notification);
    }

    /**
       Получение всех нотификаций с сортировкой
     */

    @Transactional
    public Page<Notification> allUserNotifications(User user, int page, int size, String propertyToSort) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(propertyToSort).descending());

        return notificationRepository.getNotificationsByUser(user, pageable);
    }

    public Page<Notification> getAllNotifications(User user,
                                                  int page,
                                                  int size,
                                                  String sortBy,
                                                  String sortDirection,
                                                  List<NotificationType> types,
                                                  List<NotificationStatus> statuses) {
        Sort sort = Sort.by(Sort.Direction.fromString(sortDirection), sortBy);
        PageRequest pageable = PageRequest.of(page, size, sort);

        boolean hasTypes = types != null && !types.isEmpty();
        boolean hasStatuses = statuses != null && !statuses.isEmpty();

        if (hasTypes && hasStatuses) {
            return notificationRepository.findByUserAndNotificationTypeInAndStatusIn(user, types, statuses, pageable);
        } else if (hasTypes) {
            return notificationRepository.findByUserAndNotificationTypeIn(user, types, pageable);
        } else if (hasStatuses) {
            return notificationRepository.findByUserAndStatusIn(user, statuses, pageable);
        } else {
            return notificationRepository.findByUser(user, pageable);
        }
    }

    /**
     * 5 последних непрочитанных уведомлений.
     */
    public List<Notification> getActiveNotifications(User user) {
        return notificationRepository.findTop5ByUserAndStatusOrderByCreatedAtDesc(user, NotificationStatus.NEW);
    }

    /**
     * Общее количество непрочитанных уведомлений.
     */
    public long getUnreadCount(User user) {
        return notificationRepository.countByUserAndStatus(user, NotificationStatus.NEW);
    }

    /**
     * Пометить выбранные уведомления как прочитанные.
     * @return количество обновлённых записей
     */
    @Transactional
    public int markAsRead(User user, List<Long> notificationIds) {
        if (notificationIds == null || notificationIds.isEmpty()) {
            return 0;
        }

        return notificationRepository.updateStatus(notificationIds, user, NotificationStatus.NEW,
                NotificationStatus.READIED, LocalDateTime.now());
    }

    @Transactional
    public int delete(List<Long> notificationIds) {
        if (notificationIds == null || notificationIds.isEmpty()) {
            return 0;
        }

        int count = 0;

        for (Long notificationId : notificationIds) {
            notificationRepository.deleteById(notificationId);
            count += 1;
        }

        return count;
    }
}
