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

  def change do
    create table(:subscriptions) do
      # One subscription per account; upgraded/downgraded in place.
      add :account_id, references(:accounts), null: false
      add :plan, :string, null: false
      add :status, :string, null: false, default: "incomplete"
      add :stripe_customer_id, :string
      add :stripe_subscription_id, :string
      add :current_period_end, :utc_datetime_usec

      timestamps(type: :utc_datetime_usec)
    end

    create unique_index(:subscriptions, [:account_id])
    create unique_index(:subscriptions, [:stripe_subscription_id])
    create index(:subscriptions, [:stripe_customer_id])

    create constraint(:subscriptions, :subscriptions_plan_must_be_valid,
             check: "plan IN ('team','enterprise')"
           )

    create constraint(:subscriptions, :subscriptions_status_must_be_valid,
             check: "status IN ('active','past_due','canceled','incomplete')"
           )

    create table(:watchlists) do
      add :account_id, references(:accounts), null: false
      add :name, :string, null: false
      # Repo refs in "owner/name" shape; entry shape/count validated in the
      # Watchlist changeset (Tarakan.Billing.Watchlist).
      add :entries, {:array, :string}, null: false, default: []
      add :notify, :boolean, null: false, default: true
      add :last_notified_at, :utc_datetime_usec

      timestamps(type: :utc_datetime_usec)
    end

    create index(:watchlists, [:account_id])
  end
end
