package com.ffii.fpsms.modules.common.service;

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

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.ffii.core.support.AbstractService;
import com.ffii.core.support.JdbcDao;
import com.ffii.core.utils.MapUtils;
import jakarta.annotation.Nullable;

@Service
public class AuditLogService extends AbstractService {

	public AuditLogService(JdbcDao jdbcDao) {
		super(jdbcDao);
	  }

	private static final String SQL_INSERT_AUDIT_LOG = "INSERT INTO audit_log (`tableName`, `recordId`, `modifiedBy`, `modified`, `oldData`, `newData`) "
			+ "VALUES (:tableName, :recordId, :modifiedBy, :modified, :oldData, :newData)";

	@Transactional(isolation = Isolation.SERIALIZABLE, rollbackFor = Exception.class, readOnly = false)
	public int save(String tableName, Long recordId, Long modifiedBy, Date modified, @Nullable String oldData, String newData) {
		return jdbcDao.executeUpdate(SQL_INSERT_AUDIT_LOG,MapUtils.toHashMap("tableName", tableName, "recordId", recordId,
		"modifiedBy", modifiedBy, "modified", modified,
		"oldData", oldData, "newData", newData));
	}

	@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class, readOnly = true)
	public List<Map<String, Object>> search(String tableName, Integer recordId) {

		String sql = "SELECT * FROM audit_log WHERE tableName = :tableName AND recordId = :recordId ORDER BY modified";

		return jdbcDao.queryForList(sql, Map.of("tableName", tableName, "recordId", recordId));
	}

	@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class, readOnly = true)
	public List<Map<String, Object>> getTables() {
		String sql = "SELECT DISTINCT tableName FROM audit_log";

		return jdbcDao.queryForList(sql, "");
	}

}
