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.Tag;
import com.ffii.lioner.modules.master.entity.TagRepository;
import com.ffii.lioner.modules.master.req.UpdateTagReq;
import com.ffii.core.exception.NotFoundException;
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 TagService extends AbstractBaseEntityService<Tag, Long, TagRepository> {

	private AuditLogService auditLogService;
	public TagService(JdbcDao jdbcDao, TagRepository repository, AuditLogService auditLogService) {
		super(jdbcDao, repository);
		this.auditLogService = auditLogService;
	}

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

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

	public List<Map<String,Object>> getNameList(){
		StringBuilder sql = new StringBuilder("SELECT"
			 + " t.id, "
			 + " t.name  "
			 + " FROM tag t    "
			 + " WHERE t.deleted = FALSE  "
		);

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

	public Integer getIdByName(String name) {
        StringBuilder sql = new StringBuilder("SELECT"
			+ " t.id "
			+ " FROM tag t  "
			+ " WHERE t.deleted = FALSE"
			+ " AND t.name = :name "
        );
        
        return jdbcDao.queryForInt(sql.toString(), Map.of("name", name));
    }
	
	public Tag saveOrUpdate(UpdateTagReq req) {
		Tag instance;
		if(req.getId()>0){
			instance = find(req.getId()).get();
		}
		else{
			instance = new Tag();
		}
		//=====GET OLD AUDIT LOG=====//
		String tableName = instance.getClass().getAnnotation(Table.class).name();
		StringBuilder sql = new StringBuilder("SELECT * FROM " + tableName + " WHERE id = :id");
		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 void markDeleteWithAuditLog(Tag instance){
		//=====GET OLD AUDIT LOG=====//
		String tableName = instance.getClass().getAnnotation(Table.class).name();
		StringBuilder sql = new StringBuilder("SELECT * FROM " + tableName + " WHERE id = :id");
		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 List<Map<String,Object>> list(Map<String, Object> args){
		StringBuilder sql = new StringBuilder("SELECT"
            + " t.id, "
            + " t.name "
            + " FROM tag t "
            + " WHERE t.deleted = FALSE "
		);

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

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

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

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

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

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

}


