lib/mix/tasks/pgflow_dashboard.gen.migration.ex

defmodule Mix.Tasks.PgflowDashboard.Gen.Migration do
  @shortdoc "Generates the required migration for PgFlow Dashboard"

  @moduledoc """
  Generates an Ecto migration that installs PgFlowDashboard.

  ## Usage

      mix pgflow_dashboard.gen.migration
      mix pgflow_dashboard.gen.migration --migrations-path priv/repo/migrations

  ## Options

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

  ## Generated Objects

  This migration creates the `pgflow_dashboard` PostgreSQL schema with:

  ### Views

    * `runs_with_progress` - Runs with calculated progress percentage
    * `workers_with_load` - Workers with current load metrics
    * `flow_stats` - Flow-level statistics (24h)
    * `step_states_with_tasks` - Step states with task counts

  ### Functions

    * `get_overview_metrics()` - Returns dashboard overview metrics
    * `list_runs(...)` - Paginated run listing with filters
    * `list_workers(...)` - Paginated worker listing with filters
    * `list_flows(...)` - Flow statistics

  ## Requirements

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

  ## Versioning

  PgFlowDashboard uses versioned migrations. When you upgrade the library,
  running migrations again will automatically apply any new versions.
  The current version is tracked via PostgreSQL comments.

  ## Example

      # Generate the migration
      $ mix pgflow_dashboard.gen.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,
      "create_pgflow_dashboard",
      &generate_migration_content/1,
      &message/1
    )
  end

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

    Run the migration with:
        mix ecto.migrate

    This will create:
      - pgflow_dashboard PostgreSQL schema
      - Read-only views for dashboard queries
      - PostgreSQL functions for efficient queries

    To add the dashboard to your supervision tree:

        children = [
          # ... other children
          PgFlowDashboard
        ]

    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.CreatePgflowDashboard do
      @moduledoc \"\"\"
      Installs PgFlowDashboard schema, views, and functions.

      This migration uses PgFlowDashboard's versioned migration system.
      Future library upgrades will automatically apply new versions.

      Generated by: mix pgflow_dashboard.gen.migration
      \"\"\"
      use Ecto.Migration

      def up do
        PgFlowDashboard.Migration.up()
      end

      def down do
        PgFlowDashboard.Migration.down()
      end
    end
    """
  end
end