package com.ga.common.notification;

import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.common.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class NotificationService {

    private final NotificationMapper mapper;

    public List<NotificationVO> myNotifications() {
        Long userId = SecurityUtil.getCurrentUserId();
        if (userId == null) throw new BizException(ErrorCode.UNAUTHORIZED);
        return mapper.selectByUser(userId);
    }

    public int unreadCount() {
        Long userId = SecurityUtil.getCurrentUserId();
        if (userId == null) return 0;
        return mapper.countUnread(userId);
    }

    @Transactional
    public void markRead(Long notiId) {
        Long userId = SecurityUtil.getCurrentUserId();
        if (userId == null) throw new BizException(ErrorCode.UNAUTHORIZED);
        mapper.markRead(notiId, userId);
    }

    @Transactional
    public void markAllRead() {
        Long userId = SecurityUtil.getCurrentUserId();
        if (userId == null) throw new BizException(ErrorCode.UNAUTHORIZED);
        mapper.markAllRead(userId);
    }

    @Transactional
    public void send(Long userId, String type, String title, String content, String linkUrl) {
        NotificationVO vo = new NotificationVO();
        vo.setUserId(userId);
        vo.setNotiType(type);
        vo.setTitle(title);
        vo.setContent(content);
        vo.setLinkUrl(linkUrl);
        mapper.insert(vo);
    }

    @Transactional
    public void sendBatch(List<NotificationVO> list) {
        if (list == null || list.isEmpty()) return;
        mapper.insertBatch(list);
    }
}
