defmodule Tarakan.Repo.Migrations.CreateFixPropagation do
  use Ecto.Migration

  def change do
    # A fix that settled on one repository, captured so the same pattern can be
    # closed on every other repository carrying it.
    create table(:fix_templates) do
      add :pattern_key, :string, null: false

      add :source_canonical_finding_id, references(:canonical_findings, on_delete: :delete_all),
        null: false

      add :source_repository_id, references(:repositories, on_delete: :delete_all), null: false
      add :fix_commit_sha, :string
      add :title, :string, null: false
      add :summary, :text, null: false
      # Unified diff of the fixing commit when the repository is mirrored;
      # null when only narrative evidence is available.
      add :diff, :text
      add :diff_truncated, :boolean, null: false, default: false
      add :created_by_id, references(:accounts, on_delete: :nilify_all)

      timestamps(type: :utc_datetime_usec)
    end

    create unique_index(:fix_templates, [:source_canonical_finding_id])
    create index(:fix_templates, [:pattern_key, :inserted_at])

    # One row per repository the template was carried to.
    create table(:fix_propagations) do
      add :fix_template_id, references(:fix_templates, on_delete: :delete_all), null: false

      add :canonical_finding_id, references(:canonical_findings, on_delete: :delete_all),
        null: false

      add :repository_id, references(:repositories, on_delete: :delete_all), null: false
      add :review_task_id, references(:review_tasks, on_delete: :nilify_all)
      add :status, :string, null: false, default: "open"

      timestamps(type: :utc_datetime_usec)
    end

    create unique_index(:fix_propagations, [:fix_template_id, :canonical_finding_id])
    create index(:fix_propagations, [:repository_id, :status])
  end
end
