# app/controllers/users/sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
  before_action :configure_sign_in_params, only: [:create]

  # GET /users/sign_in
  def new
    @pin_login = params[:pin].present?
    super
  end

  # POST /users/sign_in
  def create
    # PIN login para motoristas
    if params[:pin_login].present?
      handle_pin_login
    else
      super
    end
  end

  protected

  def after_sign_in_path_for(resource)
    session[:mostrar_splash] = true   # dispara a animação de abertura uma vez
    case resource.role
    when 'motorista'
      motorista_dashboard_path
    else
      dashboard_path
    end
  end

  def after_sign_out_path_for(resource_or_scope)
    new_user_session_path
  end

  def configure_sign_in_params
    devise_parameter_sanitizer.permit(:sign_in, keys: [:email, :password, :pin])
  end

  private

  def handle_pin_login
    pin = params[:pin].to_s.strip
    user = User.find_by(pin_code: pin, role: 'motorista')

    if user&.ativo?
      sign_in(user)
      session[:mostrar_splash] = true
      AuditoriaLog.registrar(user: user, acao: 'login_pin', entidade: 'User', dados_novos: { detalhes: "" }, request: request)
      redirect_to motorista_dashboard_path, notice: "Bem-vindo, #{user.nome_display}!"
    else
      flash.now[:alert] = 'PIN inválido ou motorista inativo.'
      @pin_login = true
      render :new, status: :unprocessable_entity
    end
  end
end
