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.SBUDivision;
import com.ffii.lioner.modules.master.entity.SBUDivisionRepository;
import com.ffii.lioner.modules.master.req.UpdateSBUDivisionReq;
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 SBUDivisionService extends AbstractBaseEntityService<SBUDivision, Long, SBUDivisionRepository> {

	private AuditLogService auditLogService;

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

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

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

	public void markDeleteWithAuditLog (SBUDivision 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 SBUDivision saveOrUpdate(UpdateSBUDivisionReq req) {
		SBUDivision instance;
		if(req.getId()>0){
			instance = find(req.getId()).get();
		}
		else{
			instance = new SBUDivision();
		}
		//=====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"
            + " as2.id, "
            + " as2.name "
            + " FROM apr_sbu as2  "
            + " WHERE as2.deleted = FALSE  "
		);

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

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

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

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

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

	public String getDivisionNameById(Map<String, Object> args){
		StringBuilder sql = new StringBuilder("SELECT"
			+ " as2.name "
			+ " FROM apr_sbu as2  "
			+ " WHERE as2.deleted = FALSE  "
			+ " AND as2.id = :id "
		);

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

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

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

