defmodule Mix.Tasks.SoftPos.Gen.Client do
  @moduledoc """
  Generates OAuth2.0 client credentials for SoftPOS API.

  ## Usage

      mix soft_pos.gen.client "MyPinPad Integration" "transaction:write"

  ## Arguments

    * name - A descriptive name for the client (required)
    * scopes - Space-separated list of scopes (optional, defaults to "transaction:write")

  ## Examples

      # Create client with default scopes
      mix soft_pos.gen.client "MyPinPad Production"

      # Create client with custom scopes
      mix soft_pos.gen.client "MyPinPad Test" "transaction:write transaction:read"

  The client secret will only be displayed once. Save it securely.
  """

  use Mix.Task
  alias DaProductApp.SoftPos.OauthApplications

  @shortdoc "Generate OAuth client credentials for SoftPOS API"

  @impl Mix.Task
  def run(args) do
    Mix.Task.run("app.start")

    case args do
      [name] ->
        create_client(name, "transaction:write")

      [name, scopes] ->
        create_client(name, scopes)

      _ ->
        Mix.shell().error("""
        Usage: mix soft_pos.gen.client <name> [scopes]

        Examples:
          mix soft_pos.gen.client "MyPinPad Production"
          mix soft_pos.gen.client "MyPinPad Test" "transaction:write transaction:read"
        """)
    end
  end

  defp create_client(name, scopes) do
    # Generate credentials
    uid = OauthApplications.generate_uid()
    secret = OauthApplications.generate_secret()

    attrs = %{
      name: name,
      uid: uid,
      secret: secret,
      scopes: scopes,
      redirect_uri: ""  # Not used for client_credentials grant
    }

    case OauthApplications.create_application(attrs) do
      {:ok, _application} ->
        Mix.shell().info("""

        ✅ OAuth Client Created Successfully!

        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        Client Name:   #{name}
        Client ID:     #{uid}
        Client Secret: #{secret}
        Scopes:        #{scopes}
        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

        ⚠️  IMPORTANT: Save the client secret now! It will not be shown again.

        Provide the following to MyPinPad:
        
        • Transaction Endpoint URL: https://your-domain.com/api/soft-pos/transactions
        • Access Token URL: https://your-domain.com/api/soft-pos/oauth/token
        • Client ID: #{uid}
        • Client Secret: #{secret}
        • Scope: #{scopes}
        • Grant Type: client_credentials
        • Client Authentication: client_secret_post (send credentials in body)
        • Token Header Prefix: Bearer
        """)

      {:error, changeset} ->
        Mix.shell().error("Failed to create client:")
        Mix.shell().error(inspect(changeset.errors))
    end
  end
end
