# frozen_string_literal: true
module Api
  module V1
    class MacRegisterController < ApplicationController
      skip_before_action :verify_authenticity_token

      def create
        uid = params[:uid].to_s.strip
        sn = params[:sn].to_s.strip
        render(plain: "error:uid blank") && return if uid.blank?

        mac_source = MacSource.where("mac_id is not null").where(uid: uid).first
        if mac_source
          render plain: "registered:#{mac_source.mac_id}"
        else
          mac_source = MacSource.where("mac_id is not null && uid = ''").order("mac_id").first
          if mac_source
            mac_source.uid = uid
            mac_source.sn = sn
            if mac_source.save
              render plain: "created:#{mac_source.mac_id}"
            else
              render plain: "failed:#{mac_source.errors.full_messages.join(";")}"
            end
          else
            render(plain: "failed:unable to allocate mac_id") && return
          end
        end
      end # def
    end
  end
end

### begin

#   curl -X POST --data "uid=1234567890abcde&sn=232323"  http://localhost:3000/api/v1/mac_register

#   POST http://{host}/api/v1/mac_register

#   PARAMS: uid=123456789, required => true

## Response

# Failed:

# 1.1. When uid blank:

#        error:uid blank

# 1.2  Unable to allocate mac_id by server

#        failed: unable to allocate mac_id

# 1.3  Failed to save allocated mac_id by server

#        failed: {some error messages}

# Success:

# 2.1 Already registered

#        registered:{mac_id}

# 2.2 Fresh registerd

#        created:{mac_id}

## end
