# db/migrate/YYYYMMDDHHMMSS_add_fase2_fields_to_users.rb
# Renomeie com o timestamp correto: rails g migration AddFase2FieldsToUsers
class AddFase2FieldsToUsers < ActiveRecord::Migration[7.1]
  def change
    # PIN de acesso (motoristas)
    unless column_exists?(:users, :pin_acesso)
      add_column :users, :pin_acesso, :string, limit: 4
      add_index  :users, :pin_acesso, unique: true, where: "pin_acesso IS NOT NULL"
    end

    # Status ativo/inativo — já criado em CreateUsers; guarda contra duplicação
    add_column :users, :ativo, :boolean, default: true, null: false unless column_exists?(:users, :ativo)

    # Acompanhamento de login (Devise :trackable)
    add_column :users, :sign_in_count,      :integer, default: 0, null: false unless column_exists?(:users, :sign_in_count)
    add_column :users, :current_sign_in_at, :datetime unless column_exists?(:users, :current_sign_in_at)
    add_column :users, :last_sign_in_at,    :datetime unless column_exists?(:users, :last_sign_in_at)
    add_column :users, :current_sign_in_ip, :string   unless column_exists?(:users, :current_sign_in_ip)
    add_column :users, :last_sign_in_ip,    :string   unless column_exists?(:users, :last_sign_in_ip)

    # Lockable
    add_column :users, :failed_attempts,  :integer, default: 0, null: false unless column_exists?(:users, :failed_attempts)
    add_column :users, :unlock_token,     :string   unless column_exists?(:users, :unlock_token)
    add_column :users, :locked_at,        :datetime unless column_exists?(:users, :locked_at)
    add_index  :users, :unlock_token, unique: true unless index_exists?(:users, :unlock_token)
  end
end
