class Support::Training::VideosController < Support::Training::Controller
  def index
    render_success :ok, json: videos.by_categories(params[:category_id]).map { |v| video_props(v) }
  end

  def show
    render_success :ok, json: video_props(video)
  end

  def create
    video = category.videos.build(video_params)
    if video.save
      render_success :ok, json: video_props(video)
    else
      render_error :unprocessable_entity, errors: video
    end
  end

  def update
    video.category = category
    if video.update(video_params)
      render_success :ok, json: video_props(video)
    else
      render_error :unprocessable_entity, errors: video
    end
  end

  def destroy
    if video.destroy
      render_success :ok
    else
      render_error :unprocessable_entity, errors: video
    end
  end

  private
    def category
      @category ||= ::Training::Category.find_by(id: params[:category_id])
    end

    def videos
      ::Training::Video.all
    end

    def video
      @video ||= videos.find_by(id: params[:id])
    end

    def video_params
      params.permit(:name, :url, :description)
    end

    def video_props(video)
      {
        id: video.id,
        name: video.name,
        url: video.url,
        description: video.description,
        category_id: video.category_id
      }
    end
end
