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.User_authority;
import com.ffii.fhsmsc.modules.User_group.repository.User_authorityRepository;
import com.ffii.fhsmsc.modules.User_group.req.User_authorityReq;

import jakarta.validation.Valid;

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

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

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

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

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

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