package com.backendsys.config.Mybatis.handler.timezone;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Optional;

@Component
public class TimezoneInterceptor implements HandlerInterceptor {

    @Value("${DEFAULT_TIME_ZONE}")
    private String DEFAULT_TIME_ZONE;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String timezone = request.getHeader("timezone");
        String finalTimezone = Optional.ofNullable(timezone).orElse(DEFAULT_TIME_ZONE);
        // 将 timezone 存储在 ThreadLocal 中
        TimezoneContextHolder.setTimeZone(finalTimezone);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清除 ThreadLocal 中的时区信息
        TimezoneContextHolder.clear();
    }
}