package kr.co.accura.wbx.spring.compat;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * WBX No-Code 프론트엔드 호환 — skip/limit → Spring Pageable 변환
 */
@Configuration
public class WbxPaginationConfig implements WebMvcConfigurer {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new WbxPaginationResolver());
    }

    static class WbxPaginationResolver implements HandlerMethodArgumentResolver {

        @Override
        public boolean supportsParameter(MethodParameter parameter) {
            return Pageable.class.isAssignableFrom(parameter.getParameterType());
        }

        @Override
        public Pageable resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                         NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
            String skipStr = webRequest.getParameter("skip");
            String limitStr = webRequest.getParameter("limit");
            String sortStr = webRequest.getParameter("sort");

            int skip = skipStr != null ? Integer.parseInt(skipStr) : 0;
            int limit = limitStr != null ? Integer.parseInt(limitStr) : 20;
            int page = skip / Math.max(limit, 1);

            Sort sort = sortStr != null && !sortStr.isBlank()
                    ? Sort.by(sortStr.split(","))
                    : Sort.unsorted();

            return PageRequest.of(page, limit, sort);
        }
    }
}
