lib/mix/tasks/pgflow.gen.helpers_migration.ex

defmodule Mix.Tasks.Pgflow.Gen.HelpersMigration do
  @shortdoc "Generates the required migration for PgFlow extension SQL functions"

  @moduledoc """
  Generates an Ecto migration that installs PgFlow's extension SQL functions.

  ## Usage

      mix pgflow.gen.helpers_migration
      mix pgflow.gen.helpers_migration --migrations-path priv/repo/migrations

  ## Options

    * `--migrations-path` - Path to the migrations directory.
      Defaults to `priv/repo/migrations`.

  ## Generated Functions

  This migration creates PostgreSQL functions in the `pgflow` schema:

  ### Read Functions
    * `get_flow_input(uuid)` - Get flow run input data
    * `flow_exists(text)` - Check if flow exists
    * `get_step_output(uuid, text)` - Get step output

  ### Write Functions
    * `register_worker(uuid, text, text)` - Register or heartbeat a worker
    * `mark_worker_stopped(uuid)` - Mark worker as stopped
    * `recover_stalled_tasks(double precision)` - Recover stalled tasks

  ## Requirements

  The pgflow schema must already exist. Run pgflow migrations first if needed.

  ## Example

      # Generate the migration
      $ mix pgflow.gen.helpers_migration

      # Run the migration
      $ mix ecto.migrate

  """

  use Mix.Task

  alias Mix.Tasks.Pgflow.Helpers

  @impl Mix.Task
  def run(args) do
    Helpers.write_migration(
      args,
      "add_pgflow_helpers",
      &generate_migration_content/1,
      &message/1
    )
  end

  defp message(filepath) do
    """
    Generated migration: #{filepath}

    Run the migration with:
        mix ecto.migrate

    This will create PostgreSQL functions in the pgflow schema for:
      - Worker registration and lifecycle
      - Flow input/output queries
      - Stalled task recovery

    Note: The pgflow schema must already exist. Run pgflow migrations first if needed.
    """
  end

  defp generate_migration_content(app_module) do
    """
    defmodule #{app_module}.Repo.Migrations.AddPgflowHelpers do
      @moduledoc \"\"\"
      Installs PgFlow extension SQL functions in the pgflow schema.

      Generated by: mix pgflow.gen.helpers_migration
      \"\"\"
      use Ecto.Migration

      def up do
        PgFlow.HelpersMigration.up()
      end

      def down do
        PgFlow.HelpersMigration.down()
      end
    end
    """
  end
end