import nock from "nock";
import yargs from "yargs/yargs";
import deleteCommand from "../../cmds/delete.js";
import { cleanupTest, RequestCapture, setupAuthenticatedNock, setupTestEnvironment, TEST_ACCOUNT_NAME, TEST_API_BASE, TEST_AUTH_TOKEN, TEST_PROJECT_NAME, } from "./test-utils.js";
async function executeDeleteCommand(args) {
    const yargsInstance = yargs([])
        .command(deleteCommand)
        .help(false)
        .version(false)
        .exitProcess(false);
    const commandArgs = ["delete"];
    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("--url", args.url);
    if (args.wait) {
        commandArgs.push("--wait");
    }
    if (args["self-hosted-endpoint"]) {
        commandArgs.push("--self-hosted-endpoint", args["self-hosted-endpoint"]);
    }
    return await yargsInstance.parse(commandArgs);
}
const mockPrintResult = jest.mocked(require("../../common/output.js").printResultToConsoleAndExitGracefully);
const mockPrintCriticalFailure = jest.mocked(require("../../common/output.js").printCriticalFailureToConsoleAndExit);
describe("Delete Command Integration Tests", () => {
    let requestCapture;
    beforeEach(() => {
        setupTestEnvironment();
        requestCapture = new RequestCapture();
        nock.disableNetConnect();
        jest.clearAllMocks();
    });
    afterEach(() => {
        cleanupTest();
        requestCapture.clear();
    });
    describe("SaaS version", () => {
        it("should intercept DELETE request to remove deployment", async () => {
            const testUrl = `https://test-deployment.zuplo.app`;
            const deploymentName = "test-deployment";
            const scope = setupAuthenticatedNock(nock(TEST_API_BASE))
                .delete(`/v1/accounts/${TEST_ACCOUNT_NAME}/projects/${TEST_PROJECT_NAME}/deployments/${deploymentName}`)
                .reply(200, { message: "Deployment deleted successfully" });
            scope.on("request", (req, interceptor, body) => {
                requestCapture.capture(req, interceptor, body);
            });
            await executeDeleteCommand({
                account: TEST_ACCOUNT_NAME,
                project: TEST_PROJECT_NAME,
                "api-key": TEST_AUTH_TOKEN,
                url: testUrl,
            });
            expect(scope.isDone()).toBe(true);
            expect(mockPrintResult).toHaveBeenCalled();
            const capturedRequests = requestCapture.getRequests();
            expect(capturedRequests).toMatchSnapshot("delete-deployment-saas-requests");
        });
        it("should handle deployment not found error", async () => {
            const testUrl = `https://nonexistent-deployment.zuplo.app`;
            const deploymentName = "nonexistent-deployment";
            const scope = setupAuthenticatedNock(nock(TEST_API_BASE))
                .delete(`/v1/accounts/${TEST_ACCOUNT_NAME}/projects/${TEST_PROJECT_NAME}/deployments/${deploymentName}`)
                .reply(404, { error: "Not Found", message: "Deployment not found" });
            scope.on("request", (req, interceptor, body) => {
                requestCapture.capture(req, interceptor, body);
            });
            await expect(executeDeleteCommand({
                account: TEST_ACCOUNT_NAME,
                project: TEST_PROJECT_NAME,
                "api-key": TEST_AUTH_TOKEN,
                url: testUrl,
            })).rejects.toThrow("Process would exit");
            expect(scope.isDone()).toBe(true);
            const capturedRequests = requestCapture.getRequests();
            expect(capturedRequests).toMatchSnapshot("delete-deployment-not-found-requests");
        });
        it("should handle wait option for polling deletion status", async () => {
            const testUrl = `https://test-deployment.zuplo.app`;
            const deploymentName = "test-deployment";
            const deleteScope = setupAuthenticatedNock(nock(TEST_API_BASE))
                .delete(`/v1/accounts/${TEST_ACCOUNT_NAME}/projects/${TEST_PROJECT_NAME}/deployments/${deploymentName}`)
                .reply(200, { message: "Deletion initiated" });
            const pollScope = nock("https://test-deployment.zuplo.app")
                .get("/__zuplo/build")
                .reply(200, { status: "alive" })
                .get("/__zuplo/build")
                .reply(404, { error: "Not Found" });
            [deleteScope, pollScope].forEach((scope) => {
                scope.on("request", (req, interceptor, body) => {
                    requestCapture.capture(req, interceptor, body);
                });
            });
            await executeDeleteCommand({
                account: TEST_ACCOUNT_NAME,
                project: TEST_PROJECT_NAME,
                "api-key": TEST_AUTH_TOKEN,
                url: testUrl,
                wait: true,
            });
            expect(deleteScope.isDone()).toBe(true);
            expect(pollScope.isDone()).toBe(true);
            const capturedRequests = requestCapture.getRequests();
            expect(capturedRequests).toMatchSnapshot("delete-deployment-wait-requests");
        });
    });
    describe("Self-hosted version", () => {
        it("should intercept DELETE request to self-hosted endpoint", async () => {
            const selfHostedEndpoint = "https://my-zuplo.company.com";
            const testUrl = `https://test-deployment.my-zuplo.company.com`;
            const deploymentName = "test-deployment";
            const scope = setupAuthenticatedNock(nock(selfHostedEndpoint))
                .delete(`/v1/deployments/${deploymentName}`)
                .reply(200, { message: "Deployment deleted successfully" });
            scope.on("request", (req, interceptor, body) => {
                requestCapture.capture(req, interceptor, body);
            });
            await executeDeleteCommand({
                account: TEST_ACCOUNT_NAME,
                project: TEST_PROJECT_NAME,
                "api-key": TEST_AUTH_TOKEN,
                url: testUrl,
                "self-hosted-endpoint": selfHostedEndpoint,
            });
            expect(scope.isDone()).toBe(true);
            expect(mockPrintResult).toHaveBeenCalled();
            const capturedRequests = requestCapture.getRequests();
            expect(capturedRequests).toMatchSnapshot("delete-deployment-self-hosted-requests");
        });
    });
    describe("Request validation", () => {
        it("should include correct headers and method", async () => {
            const testUrl = `https://test-deployment.zuplo.app`;
            const deploymentName = "test-deployment";
            const scope = nock(TEST_API_BASE)
                .delete(`/v1/accounts/${TEST_ACCOUNT_NAME}/projects/${TEST_PROJECT_NAME}/deployments/${deploymentName}`)
                .matchHeader("authorization", `Bearer ${TEST_AUTH_TOKEN}`)
                .reply(200, { message: "Deployment deleted successfully" });
            scope.on("request", (req, interceptor, body) => {
                requestCapture.capture(req, interceptor, body);
            });
            await executeDeleteCommand({
                account: TEST_ACCOUNT_NAME,
                project: TEST_PROJECT_NAME,
                "api-key": TEST_AUTH_TOKEN,
                url: testUrl,
            });
            expect(scope.isDone()).toBe(true);
            const capturedRequests = requestCapture.getRequests();
            expect(capturedRequests).toMatchSnapshot("delete-deployment-headers-validation");
            const request = capturedRequests[0];
            expect(request.method).toBe("DELETE");
        });
    });
});
//# sourceMappingURL=delete.integration.test.js.map