package com.yushu.web.controller.monitor;

import com.yushu.common.core.domain.AjaxResult;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 错误测试Controller
 * 用于测试错误日志记录功能
 * 
 * @author yushu
 */
@RestController
@RequestMapping("/monitor/errorTest")
public class ErrorTestController {

    /**
     * 触发运行时异常
     */
    @PreAuthorize("@ss.hasPermi('monitor:errorLog:query')")
    @GetMapping("/runtime")
    public AjaxResult testRuntimeError(@RequestParam(required = false) String message) {
        throw new RuntimeException(message != null ? message : "测试运行时异常");
    }

    /**
     * 触发空指针异常
     */
    @PreAuthorize("@ss.hasPermi('monitor:errorLog:query')")
    @GetMapping("/nullPointer")
    public AjaxResult testNullPointer() {
        String str = null;
        str.length(); // 触发NPE
        return AjaxResult.success();
    }

    /**
     * 触发数组越界异常
     */
    @PreAuthorize("@ss.hasPermi('monitor:errorLog:query')")
    @GetMapping("/arrayIndex")
    public AjaxResult testArrayIndex() {
        int[] arr = new int[3];
        int value = arr[10]; // 触发数组越界
        return AjaxResult.success(value);
    }

    /**
     * 触发算术异常（除零）
     */
    @PreAuthorize("@ss.hasPermi('monitor:errorLog:query')")
    @GetMapping("/divideByZero")
    public AjaxResult testDivideByZero() {
        int result = 10 / 0; // 触发除零异常
        return AjaxResult.success(result);
    }

    /**
     * POST请求测试（带JSON Body）
     */
    @PreAuthorize("@ss.hasPermi('monitor:errorLog:query')")
    @PostMapping("/postError")
    public AjaxResult testPostError(@RequestBody TestRequest request) {
        if ("error".equals(request.getAction())) {
            throw new RuntimeException("POST请求错误测试: " + request.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 自定义错误消息
     */
    @PreAuthorize("@ss.hasPermi('monitor:errorLog:query')")
    @GetMapping("/custom")
    public AjaxResult testCustomError(
            @RequestParam String errorType,
            @RequestParam String errorMessage) {
        throw new RuntimeException("[" + errorType + "] " + errorMessage);
    }

    // 请求体类
    public static class TestRequest {
        private String action;
        private String message;

        public String getAction() { return action; }
        public void setAction(String action) { this.action = action; }
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
    }
}
