package cn.edu.whu.boot.allocation.services.impl;

import cn.edu.whu.boot.allocation.controllers.dtos.Worker;
import cn.edu.whu.boot.allocation.entities.TaskUserRole;
import cn.edu.whu.boot.allocation.mapper.TaskUserRoleMapper;
import cn.edu.whu.boot.allocation.services.TaskUserRoleService;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class TaskUserRoleImpl implements TaskUserRoleService {

    private final TaskUserRoleMapper taskUserRoleMapper;

    private final SqlSessionFactory sqlSessionFactory;

    @Autowired
    public TaskUserRoleImpl(TaskUserRoleMapper taskUserRoleMapper, SqlSessionFactory sqlSessionFactory) {
        this.taskUserRoleMapper = taskUserRoleMapper;
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public TaskUserRole findById(int id) {
        return taskUserRoleMapper.findById(id);
    }

    @Override
    public List<TaskUserRole> findByTaskId(int taskId) {
        return taskUserRoleMapper.findByTaskId(taskId);
    }

    @Override
    public List<TaskUserRole> findByUserId(int userId) {
        return taskUserRoleMapper.findByUserId(userId);
    }

    @Override
    public List<Worker> findWorkerByTaskId(int taskId) {
        return taskUserRoleMapper.findWorkerByTaskId(taskId);
    }

    @Override
    public Optional<Integer> findWorkRoleByTaskIdAndUserId(int taskId, int userId) {
        return Optional.ofNullable(taskUserRoleMapper.findWorkRoleByTaskIdAndUserId(taskId, userId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertList(List<TaskUserRole> list) {
        if (list != null && !list.isEmpty()) {
            taskUserRoleMapper.insertForeach(list);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskUserRole update(TaskUserRole taskUserRole) {
        int id = taskUserRoleMapper.update(taskUserRole);
        return taskUserRoleMapper.findById(id);
    }

    @Override
    public List<Integer> getUserIdByTaskId(int taskId) {
        return taskUserRoleMapper.getUserIdByTaskId(taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByTaskId(int taskId) {
        taskUserRoleMapper.deleteByTaskId(taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByTaskIdAndUserId(int taskId, int userId) {
        taskUserRoleMapper.deleteByTaskIdAndUserId(taskId, userId);
    }
}
