module Api
  module V1
    class CategoriesController < ApplicationController
      before_action :set_category, only: [:show, :update, :destroy]

      def index
        @categories = Categories::Filter.call Category, params: nil

        render(json: @categories,
               each_serializer: Categories::CategorySerializer,
               status: :ok)
      end

      def show
        render(json: @category,
               serializer: Categories::CategorySerializer,
               status: :ok)
      end

      def create
        @category = Categories::Create.call! resource_params
        render(json: @category,
               status: :created)
      rescue ActiveRecord::RecordInvalid => e
        render(json: { error: e.message },
               status: :bad_request)
      end

      def update
        @category = Categories::Update.call!({ resource: @category, params: resource_params })

        render(json: @category,
               serializer: Categories::CategorySerializer,
               status: :ok)
      end

      private

      def resource_params
        params.permit(:title, :meta_title, :content)
              .to_h
              .symbolize_keys
      end

      def set_category
        @category = Category.find params[:id]
      rescue ActiveRecord::RecordNotFound
        render json: "Not Found", status: :not_found
      end
    end
  end
end
