package com.tashow.cloud.infra.controller.admin.logger;

import static com.tashow.cloud.common.pojo.CommonResult.success;
import static com.tashow.cloud.web.apilog.core.enums.OperateTypeEnum.EXPORT;
import static com.tashow.cloud.web.web.core.util.WebFrameworkUtils.getLoginUserId;

import com.tashow.cloud.common.pojo.CommonResult;
import com.tashow.cloud.common.pojo.PageParam;
import com.tashow.cloud.common.pojo.PageResult;
import com.tashow.cloud.common.util.object.BeanUtils;
import com.tashow.cloud.excel.excel.core.util.ExcelUtils;
import com.tashow.cloud.infra.controller.admin.logger.vo.apierrorlog.ApiErrorLogPageReqVO;
import com.tashow.cloud.infra.controller.admin.logger.vo.apierrorlog.ApiErrorLogRespVO;
import com.tashow.cloud.infra.dal.dataobject.logger.ApiErrorLogDO;
import com.tashow.cloud.infra.service.logger.ApiErrorLogService;
import com.tashow.cloud.web.apilog.core.annotation.ApiAccessLog;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import java.io.IOException;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/** 管理后台 - API 错误日志 */
@RestController
@RequestMapping("/infra/api-error-log")
@Validated
public class ApiErrorLogController {

  @Resource private ApiErrorLogService apiErrorLogService;

  /** 更新 API 错误日志的状态 */
  @PutMapping("/update-status")
  @PreAuthorize("@ss.hasPermission('infra:api-error-log:update-status')")
  public CommonResult<Boolean> updateApiErrorLogProcess(
      @RequestParam("id") Long id, @RequestParam("processStatus") Integer processStatus) {
    apiErrorLogService.updateApiErrorLogProcess(id, processStatus, getLoginUserId());
    return success(true);
  }

  /** 获得 API 错误日志分页 */
  @GetMapping("/page")
  @PreAuthorize("@ss.hasPermission('infra:api-error-log:query')")
  public CommonResult<PageResult<ApiErrorLogRespVO>> getApiErrorLogPage(
      @Valid ApiErrorLogPageReqVO pageReqVO) {
    PageResult<ApiErrorLogDO> pageResult = apiErrorLogService.getApiErrorLogPage(pageReqVO);
    return success(BeanUtils.toBean(pageResult, ApiErrorLogRespVO.class));
  }

  /** 导出 API 错误日志 Excel */
  @GetMapping("/export-excel")
  @PreAuthorize("@ss.hasPermission('infra:api-error-log:export')")
  @ApiAccessLog(operateType = EXPORT)
  public void exportApiErrorLogExcel(
      @Valid ApiErrorLogPageReqVO exportReqVO, HttpServletResponse response) throws IOException {
    exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
    List<ApiErrorLogDO> list = apiErrorLogService.getApiErrorLogPage(exportReqVO).getList();
    // 导出 Excel
    ExcelUtils.write(
        response,
        "API 错误日志.xls",
        "数据",
        ApiErrorLogRespVO.class,
        BeanUtils.toBean(list, ApiErrorLogRespVO.class));
  }
}
