package com.example.sjkbf.config.exception;

import cn.hutool.log.StaticLog;
import com.example.sjkbf.entity.CommonResult;

import org.apache.catalina.connector.ClientAbortException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {



    // 处理用户名密码错误异常（Spring Security 默认抛出 BadCredentialsException）
    @ExceptionHandler(BadCredentialsException.class)
    public ResponseEntity<?> handleBadCredentials(BadCredentialsException e) {

        Map<String, Object> response = new HashMap<>();
        response.put("msg", "用户名或密码错误");
        response.put("code", 4010);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(response);
    }


    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<CommonResult<String>> responseEntity(RuntimeException e) {

        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(CommonResult.failed(201,e.getMessage()));
    }


    /**
     * 处理视频文件不存在异常
     */
    @ExceptionHandler(FileNotFoundException.class)
    public ResponseEntity<String> handleFileNotFound(FileNotFoundException e) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body("Video file not found: " + e.getMessage());
    }

    /**
     * 处理转码异常
     */
    @ExceptionHandler(IOException.class)
    public ResponseEntity<String> handleTranscodeError(IOException e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("Video processing error: " + e.getMessage());
    }


    @ExceptionHandler(ClientAbortException.class)
    public void handleClientAbortException(ClientAbortException e) {
        // 仅打印警告日志，无需向上抛出
        StaticLog.info("客户端主动断开连接: {}", e.getMessage());
    }

}