# frozen_string_literal: true module Api # CompaniesController class CompaniesController < MasterController def index @companies = Company.all render json: serialized_collection.serializable_hash, status: 200 end def show @company = Company.find_by(short_name: params[:id]) render json: serialized_object.serializable_hash, status: :ok and return if @company render json: not_found_error_message, status: :not_found end def create @company = Company.new(permitted_params) render json: serialized_object.serializable_hash, status: :ok and return if @company.save render json: { error_messages: @company.errors.full_messages }, status: :unprocessable_entity end def update @company = Company.find_by(short_name: params[:id]) render json: not_found_error_message, status: :not_found and return if @company.nil? if @company.update(permitted_params) render json: serialized_object.serializable_hash, status: :ok else render json: { error_messages: @company.errors.full_messages }, status: :unprocessable_entity end end private def serialized_object Serializers::CompanySerializer.new(@company) end def serialized_collection Serializers::CompanySerializer.new(@companies.includes(logo_attachment: :blob).page(params[:page])) end def permitted_params params.permit(:name, :country, :short_name, :logo) end def not_found_error_message { error_message: "No se encontró la compañía #{params[:short_name]}" } end end end