# frozen_string_literal: true

require "lazy_object"
require "value_semantics/monkey_patched"

require_relative "sim"

class SIMRepo
	value_semantics do
		db Anything(), default: LazyObject.new { DB }
	end

	def find(iccid)
		EM::HttpRequest.new(
			"https://myaccount.keepgo.com/api/v2/line/#{iccid}/get_details",
			tls: { verify_peer: true }
		).aget(
			head: {
				"Accept" => "application/json",
				"apiKey" => CONFIG[:keepgo][:api_key],
				"accessToken" => CONFIG[:keepgo][:access_token]
			}
		).then { |req| SIM.extract(JSON.parse(req.response)&.dig("sim_card")) }
	end

	def owned_by(customer)
		customer = customer.customer_id if customer.respond_to?(:customer_id)
		promise = db.query_defer(<<~SQL, [customer])
			SELECT iccid, nickname FROM sims WHERE customer_id=$1
		SQL
		promise.then { |result|
			EMPromise.all(result.map { |row|
				find(row["iccid"]).then { |sim| sim.with(nickname: row["nickname"]) }
			})
		}
	end
end
