package com.seer.teach.user.admin.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.ResultBean;
import com.seer.teach.common.annotation.LogPrint;
import com.seer.teach.user.admin.dto.ServiceInfoDTO;
import com.seer.teach.user.admin.request.SyncPageReq;
import com.seer.teach.user.admin.request.SyncReq;
import com.seer.teach.user.admin.response.PermissionSyncLogResp;
import com.seer.teach.user.admin.service.PermissionSyncService;
import com.seer.teach.user.admin.service.SeerNacosServiceDiscovery;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/permissions")
@Tag(name = "管理端 - 权限同步")
@SaCheckLogin(type = StpUtil.TYPE)
@Validated
@RequiredArgsConstructor
@LogPrint
public class AdminPermissionController {

    @Autowired
    private PermissionSyncService syncService;

    @Autowired
    private SeerNacosServiceDiscovery seerNacosServiceDiscovery;


    /**
     * 获取服务列表
     */
    @GetMapping("/services")
    @SaCheckPermission("admin:auth:get-all-service")
    public ResultBean<List<ServiceInfoDTO>> getServices() {
        return ResultBean.success(seerNacosServiceDiscovery.getAppServices());
    }

    /**
     * 同步权限
     */
    @PostMapping("/sync")
    @SaCheckPermission("admin:auth:sync")
    public ResultBean<String> sync(@RequestBody SyncReq request) {
        syncService.syncPermissions(request.getServiceNames(), StpUtil.getLoginIdAsInt());
        return ResultBean.success("同步中...");
    }

    /**
     * 查询同步结果
     */
    @PostMapping("/sync-result")
    @SaCheckPermission("admin:auth:sync:log")
    public ResultBean<PageListBean<PermissionSyncLogResp>> getSyncResult(@RequestBody SyncPageReq req) {
        return ResultBean.success(syncService.getSyncResult(req));
    }
}