package com.itsol.quantrivanphong.report.leavetype.business;
import com.itsol.quantrivanphong.model.LeaveType;
import com.itsol.quantrivanphong.report.leavetype.dto.LeaveTypeDTO;
import com.itsol.quantrivanphong.report.leavetype.repository.LeaveTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class LeaveTypeBusiness {
    @Autowired
    LeaveTypeRepository leaveTypeRepository;

    public String addLeaveType(LeaveTypeDTO leaveTypeDTO) {
        String message;
        LeaveType leaveType = leaveTypeRepository.save(LeaveType.builder()
                .name(leaveTypeDTO.getName())
                .descriptions(leaveTypeDTO.getDescriptions())
                .status(true)
                .build());
        if (leaveType != null) {
            message = "Insert leave type success";
        } else {
            message = "Insert leave type failed";
        }
        return message;
    }

    @Transactional
    public String deleteLeaveType(int leaveTypeId) {
        String message;
        LeaveType leaveType = leaveTypeRepository.findLeaveTypeById(leaveTypeId);

        if (leaveType != null) {
            leaveTypeRepository.delete(leaveType);
            if (leaveTypeRepository.findLeaveTypeById(leaveTypeId) != null) {
                message = "Delete failed!";
            } else {
                message = "Delete success!";
            }
        } else {
            message = "Leave Form does not exist";
        }
        return message;
    }

    @Transactional
    public String updateLeaveType(LeaveTypeDTO leaveTypeDTO) {
        String message;
        LeaveType leaveType = leaveTypeRepository.findLeaveTypeById(leaveTypeDTO.getId());
        if (leaveType != null) {
                int i = leaveTypeRepository.updateLeaveType(leaveTypeDTO.getName(), leaveTypeDTO.getDescriptions(), leaveTypeDTO.getId());
                if (i == 1) {
                    message = "Update success";
                } else {
                    message = "Update failed";
                }
            } else {
                message = "Leave Type does not exist";
            }
        return message;
    }

    public List<LeaveType> getLeaveTypeList() {
        return leaveTypeRepository.findAll();
    }
}
