class CreateClubsAndBranding < ActiveRecord::Migration[7.2]
  def up
    create_table :clubs, id: :uuid do |t|
      t.string :name, null: false
      t.string :sport, null: false, default: "volleyball"
      t.string :logo_url
      t.string :primary_color, null: false, default: "#e53935"
      t.string :secondary_color, null: false, default: "#ffffff"
      t.timestamps
    end

    create_table :club_memberships, id: :uuid do |t|
      t.references :user, type: :uuid, null: false, foreign_key: true
      t.references :club, type: :uuid, null: false, foreign_key: true
      t.string :role, null: false, default: "owner"
      t.timestamps
    end
    add_index :club_memberships, %i[user_id club_id], unique: true

    add_reference :teams, :club, type: :uuid, foreign_key: true
    add_column :teams, :primary_color, :string
    add_column :teams, :secondary_color, :string

    migrate_teams_to_clubs

    change_column_null :teams, :club_id, false
  end

  def down
    change_column_null :teams, :club_id, true
    remove_column :teams, :secondary_color
    remove_column :teams, :primary_color
    remove_reference :teams, :club
    drop_table :club_memberships
    drop_table :clubs
  end

  private

  def migrate_teams_to_clubs
    say_with_time "Migrazione squadre → società" do
      Team.find_each do |team|
        owner_ut = UserTeam.find_by(team: team, role: "owner")
        next unless owner_ut

        club = Club.create!(
          name: team.name,
          sport: team.sport,
          logo_url: team.logo_url,
          primary_color: "#e53935",
          secondary_color: "#ffffff"
        )
        ClubMembership.find_or_create_by!(user: owner_ut.user, club: club) do |m|
          m.role = "owner"
        end
        team.update!(club: club)
      end
    end
  end
end
