package com.dji.sample.component.oss;

import com.dji.sample.component.oss.model.OssConfiguration;
import com.dji.sample.component.oss.service.impl.VersityGwAdminClient;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * VersityGW Admin 用户创建/删除冒烟测试（IDE 直接跑 main）。
 * <p>
 * 前提：网关已开启多租户 IAM（如 --iam-dir），否则 create-user 会失败。
 */
public class VersityGwAdminClientTest {

    private static final String ENDPOINT = "https://gt-oss-dev.geotwin.cn";
    private static final String ADMIN_ACCESS = "minioadmin";
    private static final String ADMIN_SECRET = "minioadmin";
    private static final String REGION = "us-east-1";
    private static final String BUCKET = "gtfly";

    public static void main(String[] args) {
        initOssConfig();
        VersityGwAdminClient admin = new VersityGwAdminClient();

        String tempAccess = "tmp" + UUID.randomUUID().toString().replace("-", "").substring(0, 17);
        String tempSecret = "Secret" + UUID.randomUUID().toString().replace("-", "");

        try {
            System.out.println("=== 1. list-users (before) ===");
            System.out.println(admin.listUsers());

            System.out.println("=== 2. create-user access=" + tempAccess + " role=admin ===");
            admin.createUser(tempAccess, tempSecret, "admin");
            System.out.println("  created OK");

            System.out.println("=== 3. list-users (after create) ===");
            String listed = admin.listUsers();
            System.out.println(listed);
            if (!listed.contains(tempAccess)) {
                System.err.println("  WARN: list-users 响应中未找到 " + tempAccess);
            }

            System.out.println("=== 4. temp user S3 put/delete ===");
            try (S3Client s3 = buildS3(tempAccess, tempSecret)) {
                String key = "wayline/_vgw_admin_test_" + System.currentTimeMillis() + ".txt";
                s3.putObject(b -> b.bucket(BUCKET).key(key).contentType("text/plain"),
                        RequestBody.fromBytes(("admin-user-test " + tempAccess).getBytes(StandardCharsets.UTF_8)));
                System.out.println("  put OK: " + key);
                s3.deleteObject(b -> b.bucket(BUCKET).key(key));
                System.out.println("  delete object OK");
            }

            System.out.println("=== 5. delete-user ===");
            admin.deleteUser(tempAccess);
            System.out.println("  deleted OK");

            System.out.println("=== 6. list-users (after delete) ===");
            String afterDelete = admin.listUsers();
            System.out.println(afterDelete);
            if (afterDelete.contains(tempAccess)) {
                System.err.println("  WARN: 删除后 list-users 仍包含 " + tempAccess);
            }

            System.out.println("=== 7. deleted user should NOT access S3 ===");
            try (S3Client s3 = buildS3(tempAccess, tempSecret)) {
                s3.listBuckets();
                System.err.println("  FAIL: 已删除用户仍能 listBuckets");
            } catch (S3Exception e) {
                System.out.println("  expected fail: " + e.statusCode() + " " + e.awsErrorDetails().errorMessage());
            }

            System.out.println("=== 8. delete-user idempotent (404 ok) ===");
            admin.deleteUser(tempAccess);
            System.out.println("  delete again OK");

            System.out.println("VersityGW Admin user lifecycle OK");
        } catch (Exception e) {
            System.err.println("VersityGW Admin test FAILED: " + e.getMessage());
            e.printStackTrace();
            try {
                admin.deleteUser(tempAccess);
            } catch (Exception ignore) {
                // best-effort cleanup
            }
        }
    }

    private static void initOssConfig() {
        OssConfiguration.endpoint = ENDPOINT;
        OssConfiguration.accessKey = ADMIN_ACCESS;
        OssConfiguration.secretKey = ADMIN_SECRET;
        OssConfiguration.region = REGION;
        OssConfiguration.bucket = BUCKET;
        OssConfiguration.enable = true;
    }

    private static S3Client buildS3(String access, String secret) {
        return S3Client.builder()
                .endpointOverride(URI.create(ENDPOINT))
                .region(Region.of(REGION))
                .credentialsProvider(StaticCredentialsProvider.create(
                        AwsBasicCredentials.create(access, secret)))
                .serviceConfiguration(S3Configuration.builder()
                        .pathStyleAccessEnabled(true)
                        .chunkedEncodingEnabled(false)
                        .build())
                .build();
    }
}
