import { Command } from "commander";
import { createLogger } from "../../../utils/logger.js";
import { testShopifyConnection } from "../../../utils/shopify/test-connection.js";

const logger = createLogger("test-connection");

/**
 * Creates and configures the test-connection command
 */
export function createTestConnectionCommand(): Command {
  const command = new Command("test-connection")
    .description("Test the Shopify API connection")
    .option("-s, --store <name>", "Shopify store name")
    .option("-k, --api-key <key>", "Shopify Admin API key")
    .option("-p, --password <password>", "Shopify Admin API password/token")
    .action(async (options) => {
      // Try to get credentials from environment if not provided
      const store = options.store || process.env.SHOPIFY_STORE;
      const apiKey = options.apiKey || process.env.SHOPIFY_API_KEY;
      const password = options.password || process.env.SHOPIFY_PASSWORD;

      if (!store || !apiKey || !password) {
        logger.error(
          "Missing credentials. Provide them as arguments or environment variables."
        );
        process.exit(1);
      }

      const result = await testShopifyConnection({
        storeName: store,
        apiKey,
        password,
      });

      if (result.success) {
        logger.info(`✓ ${result.message}`);
        process.exit(0);
      } else {
        logger.error(result.message);
        process.exit(1);
      }
    });

  return command;
}
