# frozen_string_literal: true

class MoveYoutubeCredentialsToClubs < ActiveRecord::Migration[7.2]
  def up
    unless column_exists?(:youtube_credentials, :club_id)
      add_reference :youtube_credentials, :club, type: :uuid, foreign_key: true
    end

    if column_exists?(:youtube_credentials, :team_id)
      say_with_time "Associa credenziali YouTube alle società" do
        execute <<~SQL.squish
          UPDATE youtube_credentials yc
          SET club_id = t.club_id
          FROM teams t
          WHERE t.id = yc.team_id AND yc.club_id IS NULL
        SQL
      end

      execute <<~SQL.squish
        DELETE FROM youtube_credentials yc
        USING youtube_credentials newer
        WHERE yc.club_id = newer.club_id
          AND yc.id <> newer.id
          AND yc.updated_at < newer.updated_at
      SQL

      change_column_null :youtube_credentials, :club_id, false
      remove_index :youtube_credentials, :team_id, if_exists: true
      remove_reference :youtube_credentials, :team, foreign_key: true
    end

    unless index_exists?(:youtube_credentials, :club_id)
      add_index :youtube_credentials, :club_id, unique: true
    end
  end

  def down
    return unless column_exists?(:youtube_credentials, :club_id)

    add_reference :youtube_credentials, :team, type: :uuid, foreign_key: true unless column_exists?(:youtube_credentials, :team_id)

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

    change_column_null :youtube_credentials, :team_id, false
    remove_index :youtube_credentials, :club_id, if_exists: true
    remove_reference :youtube_credentials, :club, foreign_key: true
    add_index :youtube_credentials, :team_id, if_not_exists: true
  end
end
