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.authority;
import com.ffii.fhsmsc.modules.User_group.repository.authorityReponsitory;
import com.ffii.fhsmsc.modules.User_group.req.authorityReq;

import jakarta.validation.Valid;

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

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

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

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

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

            if (req.getAuthority() != null) {
			if(req.getAuthority().length()>0){
				instance = find(Long.parseLong(req.getAuthority())).orElseThrow(InternalServerErrorException::new);
			} else {
				instance = new authority();
			}
		} else {
			instance = new authority();
		}
		BeanUtils.copyProperties(req, instance);
		saveAndFlush(instance);
		
		return instance;
	}    
}
