package com.smartoffice.notification;

import com.smartoffice.common.ApiException;
import com.smartoffice.user.User;
import com.smartoffice.user.UserRepository;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;

@Service
public class NotificationService {
    private final NotificationRepository notificationRepository;
    private final UserRepository userRepository;

    public NotificationService(NotificationRepository notificationRepository, UserRepository userRepository) {
        this.notificationRepository = notificationRepository;
        this.userRepository = userRepository;
    }

    @Transactional
    public void notifyUser(User user, NotificationType type, String title, String content) {
        Notification notification = new Notification();
        notification.setUser(user);
        notification.setType(type);
        notification.setTitle(title);
        notification.setContent(content);
        notificationRepository.save(notification);
    }

    public List<NotificationDto> listFor(String username) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new ApiException(404, "User not found"));
        return notificationRepository.findAllByUserOrderByCreatedAtDesc(user)
                .stream().map(NotificationDto::from).toList();
    }

    @Transactional
    public NotificationDto markRead(String username, Long id) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new ApiException(404, "User not found"));
        Notification notification = notificationRepository.findById(id)
                .orElseThrow(() -> new ApiException(404, "Notification not found"));
        if (!notification.getUser().getId().equals(user.getId())) {
            throw new ApiException(403, "Not allowed");
        }
        notification.setReadAt(Instant.now());
        return NotificationDto.from(notification);
    }
}
