package com.demo1.board.service;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo1.board.api.dto.BoardRequest;
import com.demo1.board.domain.Board;
import com.demo1.board.domain.BoardMapper;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.lotte.chamomile.module.database.mybatis.batch.BatchRequest;

@Service
@RequiredArgsConstructor
@Slf4j
public class BoardServiceImpl implements BoardService {

    private final BoardMapper boardMapper;

    @Override
    @Transactional(readOnly = true)
    public List<Board> getBoards() {
        return boardMapper.getAllBoards();
    }

    @Override
    @Transactional(readOnly = true)
    public Board getBoard(Long boardId) {
        return boardMapper.getBoardById(boardId)
                .orElseThrow(() -> new NoSuchElementException("There is no Board."));
    }

    @Override
    @Transactional
    public Board createBoard(BoardRequest request) {
        Board requestEntity = request.toEntity();
        requestEntity.onCreate();
        boardMapper.insertBoard(requestEntity);
        return boardMapper.getBoardById(requestEntity.getId())
                .orElseThrow(() -> new NoSuchElementException("There is no Board."));
    }

    @Override
    @Transactional
    public Board updateBoard(Long boardId, BoardRequest request) {
        Board requestEntity = request.toEntity(boardId);
        requestEntity.onUpdate();
        boardMapper.updateBoard(requestEntity);
        return boardMapper.getBoardById(boardId)
                .orElseThrow(() -> new NoSuchElementException("There is no Board."));
    }

    @Override
    @Transactional
    public Long deleteBoard(Long boardId) {
        boardMapper.deleteBoard(boardId);
        return boardId;
    }

	@Override
	public Page<Board> pageBoards(Pageable pageable) {
		return boardMapper.getPage(pageable);
	}

	@Override
	public void insertBulk(List<BoardRequest> list) {
		List<Board> entitys = list.stream().map(t -> t.toEntity()).collect(Collectors.toList());
		entitys.forEach(b -> b.onCreate());
		boardMapper.insertBulk(entitys);
	}
}
