package com.malk.test;

import com.malk.server.common.McR;
import com.malk.service.integration.INTPClient_User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 集成平台（IAM）联调入口
 * <p>
 * 仅 dev/test profile 暴露，生产无此端点。凭据通过 {@code application-*.yml} 的
 * {@code integration.baseUrl / clientId / clientSecret} 注入；首调用前需保证
 * 环境变量 {@code INTP_BASE_URL / INTP_CLIENT_ID / INTP_CLIENT_SECRET} 已设置。
 * <p>
 * access_token 由 {@link INTPClient_User#getAccessToken()} 内部缓存，业务端点不要求传入。
 * <p>
 * 端点清单：
 * <ul>
 *   <li>GET  {@code /test/intp/token}                — 取 token（缓存命中返回同值）</li>
 *   <li>POST {@code /test/intp/users}                — 创建用户，body: {username, password, body_ext?}</li>
 *   <li>PATCH {@code /test/intp/users/{username}}    — 修改用户，body: 字段 Map</li>
 *   <li>POST {@code /test/intp/users/delete}         — 批量删除，body: {usernames: [...]}</li>
 *   <li>GET  {@code /test/intp/users}                — 列表查询，query param 透传</li>
 * </ul>
 */
@Slf4j
@Profile({"dev", "test"})
@RestController
@RequestMapping("/test/intp")
public class INTPTestController {

    @Autowired
    private INTPClient_User intpClientUser;

    @GetMapping("token")
    McR<String> token() {
        String token = intpClientUser.getAccessToken();
        log.info("intp token len={}", token == null ? 0 : token.length());
        return McR.success(token);
    }

    @PostMapping("users")
    McR<Map> createUser(@RequestBody Map<String, Object> body) {
        String token = intpClientUser.getAccessToken();
        String username = (String) body.get("username");
        String password = (String) body.get("password");
        Map bodyExt = (Map) body.get("body_ext");
        Map data = intpClientUser.createUser(token, username, password, bodyExt);
        return McR.success(data);
    }

    @PatchMapping("users/{username}")
    McR<Boolean> updateUser(@PathVariable("username") String username,
                            @RequestBody Map<String, Object> bodyExt) {
        String token = intpClientUser.getAccessToken();
        Boolean ok = intpClientUser.updateUser(token, username, bodyExt);
        return McR.success(ok);
    }

    @PostMapping("users/delete")
    McR<Boolean> deleteUsers(@RequestBody Map<String, Object> body) {
        String token = intpClientUser.getAccessToken();
        List<String> usernames = (List<String>) body.get("usernames");
        Boolean ok = intpClientUser.deleteUsers(token, usernames);
        return McR.success(ok);
    }

    @GetMapping("users")
    McR<Map> queryUsers(@RequestParam Map<String, Object> query) {
        String token = intpClientUser.getAccessToken();
        Map data = intpClientUser.queryUsers(token, query);
        return McR.success(data);
    }
}
