package com.ruoyi.web.controller.app;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.ss.access.domain.AccessQuery;
import com.ruoyi.ss.access.domain.AccessVO;
import com.ruoyi.ss.access.service.AccessService;
import com.ruoyi.ss.access.service.AccessValidator;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 第三方认证接口
 * @author wjh
 * 2024/7/17
 */
@RestController
@RequestMapping("/app/access")
public class AppAccessController extends BaseController {

    @Autowired
    private AccessService accessService;

    @Autowired
    private AccessValidator accessValidator;

    @ApiOperation("申请accessKey")
    @PostMapping
    public AjaxResult apply() {
        return success(accessService.apply(getUserId()));
    }

    @ApiOperation("重置accessSecret")
    @PutMapping("/{accessId}/reset")
    public AjaxResult reset(@PathVariable Long accessId) {
        AccessVO access = accessService.selectAccessByAccessId(accessId);
        if (!accessValidator.isBelong(access, getUserId())) {
            return error("这不是您的秘钥，您无权操作");
        }
        return AjaxResult.success("操作成功", accessService.reset(accessId));
    }

    @ApiOperation("查询本人秘钥列表")
    @GetMapping("/list")
    public TableDataInfo list(AccessQuery query) {
        query.setUserId(getUserId());
        startPage();
        List<AccessVO> list = accessService.selectAccessList(query);
        return getDataTable(list);
    }

    @ApiOperation("删除秘钥")
    @DeleteMapping("/{id}")
    public AjaxResult del(@PathVariable Long id) {
        AccessVO access = accessService.selectAccessByAccessId(id);
        if (!accessValidator.isBelong(access, getUserId())) {
            return error("这不是您的秘钥，无法删除");
        }
        return toAjax(accessService.deleteAccessByAccessId(id));
    }

}
