package com.gxwebsoft.app.controller;

import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.app.service.AppCredentialService;
import com.gxwebsoft.app.entity.AppCredential;
import com.gxwebsoft.app.param.AppCredentialParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 应用密钥凭证控制器
 *
 * @author 科技小王子
 * @since 2026-03-28 21:29:44
 */
@Slf4j
@Tag(name = "应用密钥凭证管理")
@RestController
@RequestMapping("/api/app/app-credential")
public class AppCredentialController extends BaseController {

    @Resource
    private AppCredentialService appCredentialService;

    @Operation(summary = "分页查询应用密钥凭证")
    @GetMapping("/page")
    public ApiResult<PageResult<AppCredential>> page(AppCredentialParam param) {
        return success(appCredentialService.pageRel(param));
    }

    @Operation(summary = "查询全部应用密钥凭证")
    @GetMapping()
    public ApiResult<List<AppCredential>> list(AppCredentialParam param) {
        return success(appCredentialService.listRel(param));
    }

    @Operation(summary = "根据id查询应用密钥凭证")
    @GetMapping("/{id}")
    public ApiResult<AppCredential> get(@PathVariable("id") Integer id) {
        return success(appCredentialService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('app:appCredential:save')")
    @OperationLog
    @Operation(summary = "创建应用密钥凭证（自动生成 AppID 和 AppSecret）")
    @PostMapping()
    public ApiResult<?> save(@RequestBody AppCredential appCredential) {
        User loginUser = getLoginUser();
        if (loginUser == null) {
            return fail("请先登录");
        }
        appCredential.setUserId(loginUser.getUserId());
        // 创建并生成密钥
        AppCredential result = appCredentialService.createCredential(appCredential);
        return success("创建成功，请保存 AppSecret，该信息仅展示一次", result);
    }

    @PreAuthorize("hasAuthority('app:appCredential:update')")
    @OperationLog
    @Operation(summary = "修改应用密钥凭证（名称/类型/备注等，不含密钥）")
    @PutMapping()
    public ApiResult<?> update(@RequestBody AppCredential appCredential) {
        // 防止通过此接口直接修改 appId/appSecret
        appCredential.setAppId(null);
        appCredential.setAppSecret(null);
        if (appCredentialService.updateById(appCredential)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('app:appCredential:update')")
    @OperationLog
    @Operation(summary = "重置 AppSecret（重新生成密钥）")
    @PostMapping("/resetSecret/{id}")
    public ApiResult<?> resetSecret(@PathVariable("id") Long id) {
        try {
            AppCredential result = appCredentialService.resetSecret(id);
            return success("重置成功，请保存新 AppSecret，该信息仅展示一次", result);
        } catch (RuntimeException e) {
            return fail(e.getMessage());
        }
    }

    @PreAuthorize("hasAuthority('app:appCredential:update')")
    @OperationLog
    @Operation(summary = "禁用/启用凭证")
    @PutMapping("/status/{id}/{status}")
    public ApiResult<?> updateStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        if (appCredentialService.updateStatus(id, status)) {
            return success(status == 0 ? "已启用" : "已禁用");
        }
        return fail("操作失败");
    }

    @PreAuthorize("hasAuthority('app:appCredential:remove')")
    @OperationLog
    @Operation(summary = "删除应用密钥凭证")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (appCredentialService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('app:appCredential:save')")
    @OperationLog
    @Operation(summary = "批量添加应用密钥凭证")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<AppCredential> list) {
        if (appCredentialService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('app:appCredential:update')")
    @OperationLog
    @Operation(summary = "批量修改应用密钥凭证")
    @PutMapping("/batch")
    public ApiResult<?> updateBatch(@RequestBody BatchParam<AppCredential> batchParam) {
        if (batchParam.update(appCredentialService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('app:appCredential:remove')")
    @OperationLog
    @Operation(summary = "批量删除应用密钥凭证")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (appCredentialService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
