package com.dbnt.kcscbackend.admin.boards.service;

import com.dbnt.kcscbackend.admin.boards.entity.TnBbs;
import com.dbnt.kcscbackend.admin.boards.entity.TnBbsContents;
import com.dbnt.kcscbackend.admin.boards.repository.TnBbsContentsRepository;
import com.dbnt.kcscbackend.admin.boards.repository.TnBbsRepository;
import com.dbnt.kcscbackend.admin.config.entity.TcMenu;
import lombok.RequiredArgsConstructor;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@RequiredArgsConstructor
public class AdminBoardsService extends EgovAbstractServiceImpl {

    private final TnBbsRepository tnBbsRepository;
    private final TnBbsContentsRepository tnBbsContentsRepository;

    public List<TnBbs> selectBoardList() {
        return tnBbsRepository.findAllByOrderByBbsSeqDesc();
    }

    public Optional<TnBbs> selectBoard(Long bbsSeq) {
        return tnBbsRepository.findById(bbsSeq);
    }

    @Transactional
    public void saveBoard(TnBbs bbs, String userId) {
        if (bbs.getBbsSeq() == null) {
            bbs.setFrstCrtDt(LocalDateTime.now());
            bbs.setFrstCrtId(userId);
            bbs.setBbsAnsYn("N");
            bbs.setBbsReplYn("N");
            bbs.setUseYn("Y");
            tnBbsRepository.save(bbs);
        } else {
            TnBbs savedBoard = tnBbsRepository.findById(bbs.getBbsSeq()).orElse(null);
            savedBoard.setBbsId(bbs.getBbsId());
            savedBoard.setBbsTitle(bbs.getBbsTitle());
            savedBoard.setBbsDesc(bbs.getBbsDesc());
            //savedBoard.setUseYn("Y");
            savedBoard.setLastChgId(userId);
            savedBoard.setLastChgDt(LocalDateTime.now());
            tnBbsRepository.save(savedBoard);
        }
    }

    @Transactional
    public String deleteBoard(TnBbs bbs, String userId) {
        TnBbs savedBoard = tnBbsRepository.findById(bbs.getBbsSeq()).orElse(null);
        if (savedBoard == null) {
            return "notFind";
        } else {
            savedBoard.setUseYn("N");
            savedBoard.setLastChgDt(LocalDateTime.now());
            savedBoard.setLastChgId(userId);
            tnBbsRepository.save(savedBoard);
            return null;
        }
    }

    public List<TnBbsContents> selectPostList() {
        return tnBbsContentsRepository.findAll();
    }

}
