import {
  inquirer_default
} from "./chunk-TCWYVU4U.js";
import {
  FragmentCommand,
  require_lib
} from "./chunk-XECLOG6B.js";
import {
  FRAGMENT_ACCESS_TOKEN_PATH,
  FRAGMENT_AUTH_PATH
} from "./chunk-WS2PJBP6.js";
import {
  require_source
} from "./chunk-M5OAS5QZ.js";
import {
  __toESM,
  init_cjs_shims
} from "./chunk-7GH3YGSC.js";

// src/commands/login.ts
init_cjs_shims();
var import_core = __toESM(require_lib(), 1);
var import_chalk = __toESM(require_source(), 1);
import { AssertionError } from "node:assert";
import { writeFile } from "node:fs/promises";
var Login = class _Login extends FragmentCommand {
  static {
    this.summary = "Authenticate with FRAGMENT.";
  }
  static {
    this.description = `Authentication is scoped to one FRAGMENT Workspace.
  If you want to authenticate with another Workspace, you must create another API Client and follow the authentication flow again.
  Credentials will be written to ${import_chalk.default.magenta("~/.fragment/auth.json")}.`;
  }
  static {
    this.examples = [
      "<%= config.bin %> <%= command.id %>",
      "<%= config.bin %> <%= command.id %> --client-id <client-id> --client-secret <client-secret> --api-url <api-url> --oauth-url <oauth-url>"
    ];
  }
  static {
    this.help = "Create an API client at dashboard.fragment.dev/api-clients";
  }
  static {
    this.flags = {
      "client-id": import_core.Flags.string({
        description: "The API Client ID for your FRAGMENT Workspace.",
        required: false
      }),
      "client-secret": import_core.Flags.string({
        required: false,
        description: "The API Client Secret for your FRAGMENT Workspace"
      }),
      "api-url": import_core.Flags.string({
        required: false,
        description: "The API URL for your FRAGMENT Workspace (ex: https://api.us-west-2.fragment.dev/graphql)"
      }),
      "oauth-url": import_core.Flags.string({
        required: false,
        description: "The OAuth URL from which to retrieve your auth token (ex: https://auth.fragment.dev/oauth2/token)"
      }),
      "oauth-scope": import_core.Flags.string({
        required: false,
        description: "The OAuth Scope for your auth token (ex: https://api.us-west-2.fragment.dev/*)"
      }),
      test: import_core.Flags.boolean({
        required: false,
        description: "If set, tests stored credentials only"
      })
    };
  }
  async test() {
    const config = await this.loadFragmentAuthConfigFromDisk();
    this.assert(config, {
      message: `Unable to locate credentials. Please authenticate with 'fragment login'`
    });
    await this.validateClientCredentials(config);
  }
  async saveCredentials(auth) {
    const { token } = await this.validateClientCredentials(auth);
    await Promise.all([
      writeFile(FRAGMENT_AUTH_PATH, JSON.stringify(auth, null, 2)),
      writeFile(FRAGMENT_ACCESS_TOKEN_PATH, JSON.stringify(token, null, 2))
    ]);
    this.log(`Credentials written to ${FRAGMENT_AUTH_PATH}`);
  }
  async run() {
    const { flags } = await this.parse(_Login);
    if (flags.test) {
      this.log("--test provided, testing stored credentials");
      await this.test();
      return;
    }
    let authConfig = null;
    try {
      authConfig = await this.loadFragmentAuthConfigFromDisk();
    } catch (err) {
      if (!(err instanceof AssertionError)) {
        throw err;
      }
      this.log("Malformed credentials found. Re-authenticating...");
    }
    if (Object.keys(flags).length === 0) {
      this.log();
      if (authConfig) {
        const { shouldReprompt } = await inquirer_default.prompt([
          {
            type: "confirm",
            name: "shouldReprompt",
            message: "Already logged in. Do you want to re-authenticate?",
            default: false
          }
        ]);
        if (!shouldReprompt) {
          this.log("Not re-authenticating.");
          return;
        }
      }
      this.log(
        `
API Clients can be created at ${import_chalk.default.cyan(
          "https://dashboard.fragment.dev/go/s/api-clients"
        )}`
      );
      const { clientId } = await inquirer_default.prompt([
        {
          type: "input",
          name: "clientId",
          message: "API Client ID",
          validate: (input) => !!input
        }
      ]);
      const { clientSecret } = await inquirer_default.prompt([
        {
          type: "password",
          name: "clientSecret",
          message: "API Client Secret",
          validate: (input) => !!input
        }
      ]);
      const { apiUrl } = await inquirer_default.prompt([
        {
          type: "input",
          name: "apiUrl",
          message: "API URL",
          validate: (input) => !!input
        }
      ]);
      const { oauthUrl } = await inquirer_default.prompt([
        {
          type: "input",
          name: "oauthUrl",
          message: "OAuth URL",
          validate: (input) => !!input
        }
      ]);
      const { oauthScope } = await inquirer_default.prompt([
        {
          type: "input",
          name: "oauthScope",
          message: "OAuth Scope",
          validate: (input) => !!input
        }
      ]);
      authConfig = {
        clientId,
        clientSecret,
        apiUrl,
        oauthUrl,
        oauthScope
      };
    } else {
      this.assert(flags["client-id"], {
        message: "Must provide client ID"
      });
      this.assert(flags["client-secret"], {
        message: "Must provide client secret"
      });
      this.assert(flags["api-url"], {
        message: "Must provide API URL"
      });
      this.assert(flags["oauth-url"], {
        message: "Must provide OAuth URL"
      });
      this.assert(flags["oauth-scope"], {
        message: "Must provide OAuth Scope"
      });
      authConfig = {
        clientId: flags["client-id"],
        clientSecret: flags["client-secret"],
        apiUrl: flags["api-url"],
        oauthUrl: flags["oauth-url"],
        oauthScope: flags["oauth-scope"]
      };
    }
    await this.saveCredentials(authConfig);
  }
};

export {
  Login
};
