import nock from "nock";
import yargs from "yargs/yargs";
import variableCommand from "../../cmds/variable/index.js";
import { setupTestEnvironment, cleanupTest, setupAuthenticatedNock, RequestCapture, TEST_API_BASE, TEST_ACCOUNT_NAME, TEST_PROJECT_NAME, TEST_AUTH_TOKEN, } from "./test-utils.js";
async function executeVariableCommand(subcommand, args) {
    const yargsInstance = yargs([])
        .command(variableCommand)
        .help(false)
        .version(false)
        .exitProcess(false);
    const commandArgs = ["variable", subcommand];
    if (args.account) {
        commandArgs.push("--account", args.account);
    }
    if (args.project) {
        commandArgs.push("--project", args.project);
    }
    if (args["api-key"]) {
        commandArgs.push("--api-key", args["api-key"]);
    }
    commandArgs.push("--name", args.name);
    commandArgs.push("--value", args.value);
    commandArgs.push("--branch", args.branch);
    if (subcommand === "create") {
        if (args["is-secret"]) {
            commandArgs.push("--is-secret");
        }
        else {
            commandArgs.push("--is-secret", "false");
        }
    }
    return await yargsInstance.parse(commandArgs);
}
const mockPrintResult = jest.mocked(require("../../common/output.js").printResultToConsole);
const mockPrintDiagnostics = jest.mocked(require("../../common/output.js").printDiagnosticsToConsole);
describe("Variable Command Integration Tests", () => {
    let requestCapture;
    beforeEach(() => {
        setupTestEnvironment();
        requestCapture = new RequestCapture();
        nock.disableNetConnect();
        jest.clearAllMocks();
    });
    afterEach(() => {
        cleanupTest();
        requestCapture.clear();
    });
    describe("Variable Create Command", () => {
        it("should intercept POST request to create variable", async () => {
            const testBranch = "main";
            const testVariableName = "API_URL";
            const testValue = "https://api.example.com";
            const mockResponse = {
                name: testVariableName,
                "is-secret": false,
                value: testValue,
                branch: testBranch,
                createdOn: "2024-01-01T00:00:00Z",
                updatedOn: "2024-01-01T00:00:00Z",
            };
            const scope = setupAuthenticatedNock(nock(TEST_API_BASE))
                .post(`/v1/accounts/${TEST_ACCOUNT_NAME}/projects/${TEST_PROJECT_NAME}/branches/${encodeURIComponent(testBranch)}/variables`)
                .reply(201, mockResponse);
            scope.on("request", (req, interceptor, body) => {
                requestCapture.capture(req, interceptor, body);
            });
            await executeVariableCommand("create", {
                account: TEST_ACCOUNT_NAME,
                project: TEST_PROJECT_NAME,
                "api-key": TEST_AUTH_TOKEN,
                name: testVariableName,
                value: testValue,
                branch: testBranch,
                "is-secret": false,
            });
            expect(scope.isDone()).toBe(true);
            expect(mockPrintResult).toHaveBeenCalledWith(`${testVariableName} created successfully`);
            const capturedRequests = requestCapture.getRequests();
            expect(capturedRequests).toMatchSnapshot("variable-create-requests");
            const request = capturedRequests[0];
            expect(request.method).toBe("POST");
            expect(request.body).toEqual({
                name: testVariableName,
                isSecret: false,
                value: testValue,
            });
        });
        it("should handle secret variable creation", async () => {
            const testBranch = "production";
            const testVariableName = "DATABASE_PASSWORD";
            const testValue = "super-secret-password";
            const mockResponse = {
                name: testVariableName,
                "is-secret": true,
                value: "[REDACTED]",
                branch: testBranch,
                createdOn: "2024-01-01T00:00:00Z",
                updatedOn: "2024-01-01T00:00:00Z",
            };
            const scope = setupAuthenticatedNock(nock(TEST_API_BASE))
                .post(`/v1/accounts/${TEST_ACCOUNT_NAME}/projects/${TEST_PROJECT_NAME}/branches/${encodeURIComponent(testBranch)}/variables`)
                .reply(201, mockResponse);
            scope.on("request", (req, interceptor, body) => {
                requestCapture.capture(req, interceptor, body);
            });
            await executeVariableCommand("create", {
                account: TEST_ACCOUNT_NAME,
                project: TEST_PROJECT_NAME,
                "api-key": TEST_AUTH_TOKEN,
                name: testVariableName,
                value: testValue,
                branch: testBranch,
                "is-secret": true,
            });
            expect(scope.isDone()).toBe(true);
            expect(mockPrintResult).toHaveBeenCalledWith(`${testVariableName} created successfully`);
            const capturedRequests = requestCapture.getRequests();
            expect(capturedRequests).toMatchSnapshot("variable-create-secret-requests");
            const request = capturedRequests[0];
            expect(request.body).toEqual({
                name: testVariableName,
                isSecret: true,
                value: testValue,
            });
        });
        it("should handle variable creation error", async () => {
            const testBranch = "main";
            const testVariableName = "INVALID_VAR";
            const testValue = "test-value";
            const errorResponse = {
                error: "Bad Request",
                message: "Variable name already exists",
                statusCode: 400,
            };
            const scope = setupAuthenticatedNock(nock(TEST_API_BASE))
                .post(`/v1/accounts/${TEST_ACCOUNT_NAME}/projects/${TEST_PROJECT_NAME}/branches/${encodeURIComponent(testBranch)}/variables`)
                .reply(400, errorResponse);
            scope.on("request", (req, interceptor, body) => {
                requestCapture.capture(req, interceptor, body);
            });
            await executeVariableCommand("create", {
                account: TEST_ACCOUNT_NAME,
                project: TEST_PROJECT_NAME,
                "api-key": TEST_AUTH_TOKEN,
                name: testVariableName,
                value: testValue,
                branch: testBranch,
                "is-secret": false,
            });
            expect(scope.isDone()).toBe(true);
            expect(mockPrintDiagnostics).toHaveBeenCalled();
            const capturedRequests = requestCapture.getRequests();
            expect(capturedRequests).toMatchSnapshot("variable-create-error-requests");
        });
    });
    describe("Variable Update Command", () => {
        it("should intercept PATCH request to update variable", async () => {
            const testBranch = "main";
            const testVariableName = "API_URL";
            const testValue = "https://api-v2.example.com";
            const mockResponse = {
                name: testVariableName,
                "is-secret": false,
                value: testValue,
                branch: testBranch,
                createdOn: "2024-01-01T00:00:00Z",
                updatedOn: "2024-01-02T00:00:00Z",
            };
            const scope = setupAuthenticatedNock(nock(TEST_API_BASE))
                .patch(`/v1/accounts/${TEST_ACCOUNT_NAME}/projects/${TEST_PROJECT_NAME}/branches/${encodeURIComponent(testBranch)}/variables/${encodeURIComponent(testVariableName)}`)
                .reply(200, mockResponse);
            scope.on("request", (req, interceptor, body) => {
                requestCapture.capture(req, interceptor, body);
            });
            await executeVariableCommand("update", {
                account: TEST_ACCOUNT_NAME,
                project: TEST_PROJECT_NAME,
                "api-key": TEST_AUTH_TOKEN,
                name: testVariableName,
                value: testValue,
                branch: testBranch,
            });
            expect(scope.isDone()).toBe(true);
            expect(mockPrintResult).toHaveBeenCalledWith(`${testVariableName} updated successfully`);
            const capturedRequests = requestCapture.getRequests();
            expect(capturedRequests).toMatchSnapshot("variable-update-requests");
            const request = capturedRequests[0];
            expect(request.method).toBe("PATCH");
            expect(request.body).toEqual({
                value: testValue,
            });
        });
        it("should handle variable not found error", async () => {
            const testBranch = "main";
            const testVariableName = "NONEXISTENT_VAR";
            const testValue = "new-value";
            const errorResponse = {
                error: "Not Found",
                message: "Variable not found",
                statusCode: 404,
            };
            const scope = setupAuthenticatedNock(nock(TEST_API_BASE))
                .patch(`/v1/accounts/${TEST_ACCOUNT_NAME}/projects/${TEST_PROJECT_NAME}/branches/${encodeURIComponent(testBranch)}/variables/${encodeURIComponent(testVariableName)}`)
                .reply(404, errorResponse);
            scope.on("request", (req, interceptor, body) => {
                requestCapture.capture(req, interceptor, body);
            });
            await executeVariableCommand("update", {
                account: TEST_ACCOUNT_NAME,
                project: TEST_PROJECT_NAME,
                "api-key": TEST_AUTH_TOKEN,
                name: testVariableName,
                value: testValue,
                branch: testBranch,
            });
            expect(scope.isDone()).toBe(true);
            expect(mockPrintDiagnostics).toHaveBeenCalled();
            const capturedRequests = requestCapture.getRequests();
            expect(capturedRequests).toMatchSnapshot("variable-update-error-requests");
        });
    });
    describe("Request validation", () => {
        it("should include correct headers and content-type", async () => {
            const testBranch = "main";
            const testVariableName = "TEST_VAR";
            const testValue = "test-value";
            const mockResponse = {
                name: testVariableName,
                "is-secret": false,
                value: testValue,
                branch: testBranch,
                createdOn: "2024-01-01T00:00:00Z",
                updatedOn: "2024-01-01T00:00:00Z",
            };
            const scope = nock(TEST_API_BASE)
                .post(`/v1/accounts/${TEST_ACCOUNT_NAME}/projects/${TEST_PROJECT_NAME}/branches/${encodeURIComponent(testBranch)}/variables`)
                .matchHeader("authorization", `Bearer ${TEST_AUTH_TOKEN}`)
                .matchHeader("content-type", "application/json")
                .reply(201, mockResponse);
            scope.on("request", (req, interceptor, body) => {
                requestCapture.capture(req, interceptor, body);
            });
            await executeVariableCommand("create", {
                account: TEST_ACCOUNT_NAME,
                project: TEST_PROJECT_NAME,
                "api-key": TEST_AUTH_TOKEN,
                name: testVariableName,
                value: testValue,
                branch: testBranch,
                "is-secret": false,
            });
            expect(scope.isDone()).toBe(true);
            const capturedRequests = requestCapture.getRequests();
            expect(capturedRequests).toMatchSnapshot("variable-headers-validation");
        });
    });
});
//# sourceMappingURL=variable.integration.test.js.map