class MoveSubscriptionsToClubs < ActiveRecord::Migration[7.2]
  def up
    unless column_exists?(:subscriptions, :club_id)
      add_reference :subscriptions, :club, type: :uuid, foreign_key: true, index: { unique: true }
    end

    execute <<~SQL.squish
      UPDATE subscriptions SET club_id = teams.club_id
      FROM teams WHERE subscriptions.team_id = teams.id AND subscriptions.club_id IS NULL
    SQL

    if column_exists?(:subscriptions, :team_id)
      remove_index :subscriptions, :team_id if index_exists?(:subscriptions, :team_id)
      remove_reference :subscriptions, :team
    end

    change_column_null :subscriptions, :club_id, false if column_exists?(:subscriptions, :club_id)
  end

  def down
    add_reference :subscriptions, :team, type: :uuid, foreign_key: true, index: { unique: true } unless column_exists?(:subscriptions, :team_id)

    execute <<~SQL.squish
      UPDATE subscriptions SET team_id = (
        SELECT teams.id FROM teams WHERE teams.club_id = subscriptions.club_id ORDER BY teams.created_at LIMIT 1
      )
    SQL

    remove_reference :subscriptions, :club if column_exists?(:subscriptions, :club_id)
    change_column_null :subscriptions, :team_id, false
  end
end
