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

  def change do
    create table(:finding_regressions) do
      add :canonical_finding_id, references(:canonical_findings, on_delete: :delete_all),
        null: false

      add :repository_id, references(:repositories, on_delete: :delete_all), null: false
      # The commit the finding was last believed fixed at, and when.
      add :fixed_commit_sha, :string
      add :fixed_at, :utc_datetime_usec
      # The commit the finding was seen at again.
      add :detected_commit_sha, :string, null: false
      add :detected_by_scan_id, references(:scans, on_delete: :nilify_all)

      timestamps(type: :utc_datetime_usec)
    end

    # One regression row per (finding, reappearance commit) keeps repeated
    # scans of the same commit from stacking duplicates. Named explicitly
    # because the derived name exceeds Postgres's 63-character identifier cap.
    create unique_index(:finding_regressions, [:canonical_finding_id, :detected_commit_sha],
             name: :finding_regressions_unique_detection_index
           )

    create index(:finding_regressions, [:repository_id, :inserted_at])
  end
end
