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.Category;
import com.ffii.lioner.modules.master.entity.CategoryRepository;
import com.ffii.lioner.modules.master.entity.PromotionChannel;
import com.ffii.lioner.modules.master.req.UpdateCategoryReq;
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 CategoryService extends AbstractBaseEntityService<Category, Long, CategoryRepository> {

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

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

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

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

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

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

	public Category saveOrUpdate(UpdateCategoryReq req) {
		Category instance;
		if(req.getId()>0){
			instance = find(req.getId()).get();
		}
		else{
			instance = new Category();
		}
		//=====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 (Category 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"
            + " c.id, "
            + " c.name, "
            + " c.description "
            + " FROM category c "
            + " WHERE c.deleted = FALSE "
		);

		if (args != null) {
			if (args.containsKey(Params.ID)) sql.append(" AND c.id = :id");
			if (args.containsKey(Params.NAME)) sql.append(" AND c.name LIKE :name");
			if (args.containsKey("description")) sql.append(" AND c.description LIKE :description");

		}
		sql.append(" ORDER BY c.name asc");

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

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

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

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

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


