module Admin
  class AuthController < Admin::BaseController
    skip_before_action :require_admin_login, only: %i[new create]

    def new
      redirect_to admin_root_path if admin_logged_in?
    end

    def create
      account = AdminAccount.find_by(username: params[:username]&.strip)
      if account&.authenticate(params[:password])
        session[:admin_account_id] = account.id
        redirect_to session.delete(:admin_return_to) || admin_root_path, notice: "Accesso effettuato"
      else
        flash.now[:alert] = "Username o password non validi"
        render :new, status: :unauthorized
      end
    end

    def destroy
      reset_session
      redirect_to admin_login_path, notice: "Disconnesso"
    end
  end
end
