defmodule Mv.Repo.Migrations.AddCycleEndToMembershipFeeCycles do
  @moduledoc """
  Adds the denormalized `cycle_end` column to `membership_fee_cycles`.

  The column is added nullable, backfilled from `cycle_start + interval` for every
  existing row (via `Mv.MembershipFees.CycleEndBackfill`), and only then made
  `NOT NULL`. Going forward the column is populated at create time by the
  `SetCycleEnd` change.
  """

  use Ecto.Migration

  def up do
    alter table(:membership_fee_cycles) do
      add :cycle_end, :date
    end

    flush()

    {:ok, _count} = Mv.MembershipFees.CycleEndBackfill.run()

    alter table(:membership_fee_cycles) do
      modify :cycle_end, :date, null: false
    end
  end

  def down do
    alter table(:membership_fee_cycles) do
      remove :cycle_end
    end
  end
end
