defmodule WhoNeedHelp.Repo.Migrations.ExtendReportsForActivities do
  use Ecto.Migration

  def up do
    execute "ALTER TABLE reports DROP CONSTRAINT IF EXISTS report_exactly_one_target"

    alter table(:reports) do
      add :activity_id, references(:activities, type: :binary_id, on_delete: :nilify_all)

      add :activity_message_id,
          references(:activity_messages, type: :binary_id, on_delete: :nilify_all)
    end

    create index(:reports, [:activity_id])
    create index(:reports, [:activity_message_id])

    create constraint(:reports, :report_exactly_one_target,
             check:
               "num_nonnulls(request_id, assignment_id, message_id, activity_id, activity_message_id) = 1"
           )
  end

  def down do
    execute "ALTER TABLE reports DROP CONSTRAINT IF EXISTS report_exactly_one_target"
    drop index(:reports, [:activity_message_id])
    drop index(:reports, [:activity_id])

    alter table(:reports) do
      remove :activity_message_id
      remove :activity_id
    end

    create constraint(:reports, :report_exactly_one_target,
             check: "num_nonnulls(request_id, assignment_id, message_id) = 1"
           )
  end
end
