class Admin::RequestsController < Admin::BaseController
  def index
    @requested_entries = Entry.requested
                              .includes(:requested_by)
                              .order(created_at: :desc)

    @approved_entries = Entry.approved
                             .includes(:requested_by)
                             .order(updated_at: :desc)
  end

  def show
    @entry = Entry.find(params[:id])
  end

  def edit
    @entry = Entry.find(params[:id])
  end

  def update
    @entry = Entry.find(params[:id])

    if @entry.update(entry_params)
      redirect_to admin_request_path(@entry), notice: "Request updated successfully."
    else
      flash.now[:alert] = "Error updating request."
      render :edit, status: :unprocessable_entity
    end
  end

  def approve
    @entry = Entry.find(params[:id])
    @user = @entry.requested_by

    @user.invite_by!(current_user)

    @entry.update!(status: :approved)
    InvitationMailer.invite(@user, approved_entry: @entry).deliver_later

    redirect_to admin_requests_path, notice: "Request approved and invitation sent to #{@user.email}."
  end

  def reject
    @entry = Entry.find(params[:id])
    @user = @entry.requested_by

    entry_preview = [ @entry.fi, @entry.en, @entry.sv, @entry.no, @entry.ru, @entry.de ].compact.first || "Entry"

    @entry.destroy!
    @user.destroy! if @user.requested_entries.count.zero?

    redirect_to admin_requests_path, notice: "Request '#{entry_preview}' has been rejected and deleted."
  end

  private

  def entry_params
    params.require(:entry).permit(:category, :fi, :en, :sv, :no, :ru, :de, :notes)
  end
end
