package com.ffii.fhsmsc.modules.User_group.service;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ffii.core.exception.InternalServerErrorException;
import com.ffii.core.support.AbstractBaseEntityService;
import com.ffii.core.support.JdbcDao;
import com.ffii.core.utils.BeanUtils;
import com.ffii.fhsmsc.modules.User_group.enity.UserDelegation;
import com.ffii.fhsmsc.modules.User_group.repository.UserDelegationRepository;
import com.ffii.fhsmsc.modules.User_group.req.UserDelegationReq;

import jakarta.validation.Valid;

@Service
public class UserDelegationService extends AbstractBaseEntityService<UserDelegation, Long, UserDelegationRepository> {
    public UserDelegationService(JdbcDao jdbcDao, UserDelegationRepository repository) {
        super(jdbcDao, repository);
    }
    
    public List<Map<String, Object>> search(Map<String, Object> args) {
		StringBuilder sql = new StringBuilder("SELECT"
		+ " fi.*"
		+ " FROM User_Delegation fi"
		+ " WHERE 1=1");

		if (args != null) {
			if (args.containsKey("User_ID")) sql.append(" AND fi.User_ID = :User_ID");
			if (args.containsKey("R_ship_Creator")) sql.append(" AND fi.R_ship_Creator = :R_ship_Creator");
		}

		sql.append(" ORDER BY fi.User_ID");

		return jdbcDao.queryForList(sql.toString(), args);
	}

    @Transactional(rollbackFor = Exception.class)
	public UserDelegation saveOrUpdate(@Valid UserDelegationReq req) {
		    UserDelegation instance;

            if (req.getUser_ID() != null) {
			if(req.getUser_ID()>0){
				instance = find(req.getUser_ID()).orElseThrow(InternalServerErrorException::new);
			} else {
				instance = new UserDelegation();
			}
		} else {
			instance = new UserDelegation();
		}
		BeanUtils.copyProperties(req, instance);
		saveAndFlush(instance);
		
		return instance;
	}    
}