class UserThemeSlotsController < ApplicationController
  wrap_parameters false

  def index
    return head :unauthorized unless current_user

    render json: current_user
                 .theme_slots
                 .order(:base_theme, :slot_no)
                 .map { |slot| slot.serializable_hash }
  end

  def update
    return head :unauthorized unless current_user

    base_theme = params[:base_theme].to_s
    slot_no = params[:slot_no].to_i
    tokens = params[:tokens]

    unless UserThemeSlot::BASE_THEMES.include?(base_theme)
      return render_validation_error fields: { base_theme: ['値が不正です．'] }
    end
    unless UserThemeSlot::SLOT_NOS.include?(slot_no)
      return render_validation_error fields: { slot_no: ['値が不正です．'] }
    end
    unless tokens.is_a?(ActionController::Parameters) || tokens.is_a?(Hash)
      return render_validation_error fields: { tokens: ['JSON object で指定してください．'] }
    end

    slot = UserThemeSlot.find_or_initialize_by(user: current_user,
                                               base_theme:,
                                               slot_no:)
    slot.tokens = tokens.is_a?(ActionController::Parameters) ? tokens.to_unsafe_h : tokens
    slot.save!

    render json: slot.serializable_hash, status: :ok
  end
end
