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.UserGroupMembers;
import com.ffii.fhsmsc.modules.User_group.repository.UserGroupMembersRepository;
import com.ffii.fhsmsc.modules.User_group.req.UserGroupMembersReq;

import jakarta.validation.Valid;

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

		if (args != null) {
			if (args.containsKey("User_Grp_Org_ID")) sql.append(" AND fi.User_Grp_Org_ID = :User_Grp_Org_ID");
			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_Grp_Org_ID");

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

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

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