package com.dbnt.faisp.main.userInfo.service;

import com.dbnt.faisp.main.authMgt.service.AuthMgtService;
import com.dbnt.faisp.main.userInfo.mapper.UserInfoMapper;
import com.dbnt.faisp.main.userInfo.model.UserAlarm;
import com.dbnt.faisp.main.userInfo.repository.UserAlarmRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UserAlarmService {
  private final AuthMgtService authMgtService;
  private final UserAlarmRepository userAlarmRepository;
  private final UserInfoMapper userInfoMapper;

  @Transactional
  public void saveAlarmList(List<UserAlarm> alarmList) {
    userAlarmRepository.saveAll(alarmList);
  }

  public UserAlarm makeUserAlarm(LocalDateTime dateTime, Integer userSeq,
                                 Integer refDocKey, Integer menuKey, String alarmMsg){
    UserAlarm alarm = new UserAlarm();
    alarm.setAlarmKey(dateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
    alarm.setUserSeq(userSeq);
    alarm.setRefDocKey(refDocKey);
    alarm.setMenuKey(menuKey);
    alarm.setAlarmMsg(alarmMsg);
    alarm.setViewYn("N");
    alarm.setWrtDt(dateTime);
    return alarm;
  }

  public List<UserAlarm> selectAlarmList(UserAlarm userAlarm) {
    return userInfoMapper.selectAlarmList(userAlarm);
  }
  public Integer selectAlarmListCnt(UserAlarm userAlarm) {
    return userInfoMapper.selectAlarmListCnt(userAlarm);
  }

  public void sendAlarmToApprvUser(Integer planKey, String wrtOrgan, String apprvAuth, Integer menuKey, String msg){
    List<Integer> apprvUserList = authMgtService.selectApprvUserList(wrtOrgan, menuKey, apprvAuth);
    List<UserAlarm> alarmList = new ArrayList<>();
    LocalDateTime dateTime = LocalDateTime.now();
    for(Integer userSeq: apprvUserList){
      UserAlarm alarm = makeUserAlarm
          (dateTime, userSeq, planKey, menuKey, msg);
      alarmList.add(alarm);
    }
    saveAlarmList(alarmList);
  }
  public void sendAlarmToWrtUser(Integer planKey, Integer userSeq, Integer menuKey, String msg){
    List<UserAlarm> alarmList = new ArrayList<>();
    UserAlarm alarm = makeUserAlarm
        (LocalDateTime.now(), userSeq, planKey, menuKey, msg);
    alarmList.add(alarm);
    saveAlarmList(alarmList);
  }
}
