package com.xunhong.erp.turbo.auth.controller;

import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.anji.captcha.util.StringUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "Captcha", description = "验证码管理")
@RestController("authCaptchaController")
@RequestMapping("/auth")
@RequiredArgsConstructor
public class CaptchaController {
	private final CaptchaService captchaService;

	public static String getRemoteId(HttpServletRequest request) {
		String xfwd = request.getHeader("X-Forwarded-For");
		String ip = getRemoteIpFromXfwd(xfwd);
		String ua = request.getHeader("user-agent");
		if (StringUtils.isNotBlank(ip)) {
			return ip + ua;
		}
		return request.getRemoteAddr() + ua;
	}

	private static String getRemoteIpFromXfwd(String xfwd) {
		if (StringUtils.isNotBlank(xfwd)) {
			String[] ipList = xfwd.split(",");
			return StringUtils.trim(ipList[0]);
		}
		return null;
	}

	@PostMapping("/captcha/get")
	public ResponseModel get(@RequestBody CaptchaVO data, HttpServletRequest request) {
		assert request.getRemoteHost() != null;
		data.setBrowserInfo(getRemoteId(request));
		return captchaService.get(data);
	}

	@PostMapping("/captcha/check")
	public ResponseModel check(@RequestBody CaptchaVO data, HttpServletRequest request) {
		data.setBrowserInfo(getRemoteId(request));
		return captchaService.check(data);
	}

	@PostMapping("/captcha/verify")
	public ResponseModel verify(@RequestBody CaptchaVO data, HttpServletRequest request) {
		return captchaService.verification(data);
	}
}
