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.UserGroupAdmin;
import com.ffii.fhsmsc.modules.User_group.repository.UserGroupAdminRepository;
import com.ffii.fhsmsc.modules.User_group.req.UserGroupAdminReq;

import jakarta.validation.Valid;

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

		if (args != null) {
			if (args.containsKey("FB_id")) sql.append(" AND fi.FB_id = :FB_id");
			if (args.containsKey("FB_outlet_id")) sql.append(" AND fi.FB_outlet_id = :FB_outlet_id");
			if (args.containsKey("FB_outlet_district")) sql.append(" AND fi.FB_outlet_district = :FB_outlet_district");
		}

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

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

    @Transactional(rollbackFor = Exception.class)
	public UserGroupAdmin saveOrUpdate(@Valid UserGroupAdminReq req) {
		UserGroupAdmin 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 UserGroupAdmin();
			}
		} else {
			instance = new UserGroupAdmin();
		}
		BeanUtils.copyProperties(req, instance);
		saveAndFlush(instance);
		
		return instance;
	}    
}

