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.ClientDepartment;
import com.ffii.lioner.modules.master.entity.ClientDepartmentRepository;
import com.ffii.lioner.modules.master.req.UpdateClientDepartmentReq;
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 ClientDepartmentService extends AbstractBaseEntityService<ClientDepartment, Long, ClientDepartmentRepository> {

	private AuditLogService auditLogService;

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

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

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

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

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

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

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

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

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

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

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

