package com.keao.edu.common.tenant;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class TenantInterceptor extends HandlerInterceptorAdapter {

	private static final String TENANT_ID = "tenantId";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String tenantId = request.getHeader(TENANT_ID);
		if (StringUtils.isBlank(tenantId)) {
			tenantId = request.getParameter(TENANT_ID);
		}
		TenantContextHolder.setTenantId(tenantId);

		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		TenantContextHolder.clearTenantId();
	}

}
