package com.ffii.lioner.modules.master.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ffii.core.utils.BeanUtils;
import org.springframework.stereotype.Service;

import com.ffii.lioner.modules.common.SecurityUtils;
import com.ffii.lioner.modules.common.service.AuditLogService;
import com.ffii.lioner.modules.master.entity.AppreciationCategory;
import com.ffii.lioner.modules.master.entity.AppreciationCategoryRepository;
import com.ffii.lioner.modules.master.req.UpdateAppreciationCategoryReq;
import com.ffii.core.support.AbstractBaseEntityService;
import com.ffii.core.support.JdbcDao;
import com.ffii.core.utils.JsonUtils;
import com.ffii.core.utils.Params;

import jakarta.persistence.Table;

@Service
public class AppreciationCategoryService extends AbstractBaseEntityService<AppreciationCategory, Long, AppreciationCategoryRepository> {

	private AuditLogService auditLogService;

	public AppreciationCategoryService(JdbcDao jdbcDao, AppreciationCategoryRepository repository, AuditLogService auditLogService) {
		super(jdbcDao, repository);
		this.auditLogService = auditLogService;
	}

	public Map<String,Object> getAuditLogObject(Map<String,Object> req){
		StringBuilder sql = new StringBuilder("SELECT"
			+ " ac.id,    "
			+ " ac.created,    "
			+ " ac.createdBy AS createdById,    "
			+ " u1.name AS createdBy,    "
			+ " ac.version,    "
			+ " ac.modified,    "
			+ " ac.modifiedBy AS modifiedById,    "
			+ " u2.name AS modifiedBy, "
			+ " ac.deleted, "
			+ " ac.name "
			+ " FROM apr_category ac "
			+ " LEFT JOIN `user` u1 ON u1.id = ac.createdBy     "
			+ " LEFT JOIN `user` u2 ON u2.id = ac.modifiedBy      "
			+ " WHERE ac.id = :id    "
		);

		return jdbcDao.queryForMap(sql.toString(), req).get();
	}

	public void markDeleteWithAuditLog (AppreciationCategory instance){
		//=====GET OLD AUDIT LOG=====//
		String tableName = instance.getClass().getAnnotation(Table.class).name();
		Map<String,Object> oldValueObject = new HashMap<String,Object>();
		Map<String,Object> newValueObject = new HashMap<String,Object>();
		
		if (instance != null && instance.getId() != null && instance.getId() > 0) {
			Map<String,Object> input = Map.of("id", instance.getId());
			Map<String,Object> logData= getAuditLogObject(input);
			oldValueObject = logData;
		}
		//=====GET OLD AUDIT LOG=====//
		markDelete(instance.getId());
		
		//=====GET NEW AUDIT LOG=====//
		if (instance != null && instance.getId() != null && instance.getId() > 0) {
			Map<String,Object> input = Map.of("id", instance.getId());
			Map<String,Object> logData= getAuditLogObject(input);
			newValueObject = logData;
		}


		if(auditLogService.compareMaps(newValueObject,oldValueObject).size() != 0 ||
			auditLogService.compareMaps(oldValueObject,newValueObject).size() != 0
		){
			auditLogService.save(
				tableName,
				instance.getId(),
				instance.getName(),
				SecurityUtils.getUser() != null ? SecurityUtils.getUser().get().getId() : null,
				new Date(),
				JsonUtils.toJsonString(auditLogService.compareMaps(newValueObject,oldValueObject)),
				JsonUtils.toJsonString(auditLogService.compareMaps(oldValueObject,newValueObject)));
		}
		//=====GET NEW AUDIT LOG=====//
	}

	public AppreciationCategory saveOrUpdate(UpdateAppreciationCategoryReq req) {
		AppreciationCategory instance;
		if(req.getId()>0){
			instance = find(req.getId()).get();
		}
		else{
			instance = new AppreciationCategory();
		}
		//=====GET OLD AUDIT LOG=====//
		String tableName = instance.getClass().getAnnotation(Table.class).name();
		Map<String,Object> oldValueObject = new HashMap<String,Object>();
		Map<String,Object> newValueObject = new HashMap<String,Object>();
		
		if (instance != null && instance.getId() != null && instance.getId() > 0) {
			Map<String,Object> input = Map.of("id", instance.getId());
			Map<String,Object> logData= getAuditLogObject(input);
			oldValueObject = logData;
		}
		//=====GET OLD AUDIT LOG=====//

		BeanUtils.copyProperties(req,instance);
		instance = save(instance);

		//=====GET NEW AUDIT LOG=====//
		if (instance != null && instance.getId() != null && instance.getId() > 0) {
			Map<String,Object> input = Map.of("id", instance.getId());
			Map<String,Object> logData= getAuditLogObject(input);
			newValueObject = logData;
		}


		if(auditLogService.compareMaps(newValueObject,oldValueObject).size() != 0 ||
			auditLogService.compareMaps(oldValueObject,newValueObject).size() != 0
		){
			auditLogService.save(
				tableName,
				instance.getId(),
				instance.getName(),
				SecurityUtils.getUser() != null ? SecurityUtils.getUser().get().getId() : null,
				new Date(),
				JsonUtils.toJsonString(auditLogService.compareMaps(newValueObject,oldValueObject)),
				JsonUtils.toJsonString(auditLogService.compareMaps(oldValueObject,newValueObject)));
		}
		//=====GET NEW AUDIT LOG=====//

		return instance;
	}

	public List<Map<String,Object>> list(Map<String, Object> args){
		StringBuilder sql = new StringBuilder("SELECT"
            + " ac.id, "
            + " ac.name "
            + " FROM apr_category ac  "
            + " WHERE ac.deleted = FALSE  "
		);

		if (args != null) {
			if (args.containsKey(Params.ID)) sql.append(" AND ac.id = :id");
			if (args.containsKey(Params.NAME)) sql.append(" AND ac.name LIKE :name");
		}
		sql.append(" ORDER BY ac.name asc");

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

	public List<Map<String,Object>> listDepartmentCombo(Map<String, Object> args){
		StringBuilder sql = new StringBuilder("SELECT"
            + " ac.id, "
			+ " ac.id as `key`, "
            + " ac.name as label"
            + " FROM apr_category ac "
            + " WHERE ac.deleted = FALSE "
		);

		sql.append(" ORDER BY ac.name asc");

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

	public boolean isNameTaken(String name, Long id) {
        StringBuilder sql = new StringBuilder("SELECT"
            + " Count(ac.id) "
            + " FROM apr_category ac  "
            + " WHERE ac.deleted = FALSE  "
            + " AND ac.name = :name "
			+ " AND ac.id != :id"
        );
        
        return jdbcDao.queryForBoolean(sql.toString(), Map.of("name", name, "id", id));
    }

	public Integer getIdByName(String name) {
        StringBuilder sql = new StringBuilder("SELECT"
			+ " ac.id "
			+ " FROM apr_category ac  "
			+ " WHERE ac.deleted = FALSE "
			+ " AND ac.name = :name "
        );
        
        return jdbcDao.queryForInt(sql.toString(), Map.of("name", name));
    }
}

