require "json"

module JosieHealth
  module CLI
    class Config
      CONFIG_DIR  = Path.home / ".config" / "josie-health"
      CONFIG_FILE = CONFIG_DIR / "config.json"

      property api_key : String?
      property api_endpoint : String
      property user_id : String?

      def initialize(@api_key = nil, @api_endpoint = "https://api.josie.health", @user_id = nil)
      end

      def self.load : Config
        return Config.new unless File.exists?(CONFIG_FILE)

        begin
          data = JSON.parse(File.read(CONFIG_FILE))
          Config.new(
            api_key: data["api_key"]?.try(&.as_s?),
            api_endpoint: data["api_endpoint"]?.try(&.as_s?) || "https://api.josie.health",
            user_id: data["user_id"]?.try(&.as_s?)
          )
        rescue
          Config.new
        end
      end

      def save
        Dir.mkdir_p(CONFIG_DIR) unless Dir.exists?(CONFIG_DIR)

        data = {} of String => String
        data["api_key"] = @api_key.not_nil! if @api_key
        data["api_endpoint"] = @api_endpoint
        data["user_id"] = @user_id.not_nil! if @user_id

        File.write(CONFIG_FILE, data.to_pretty_json)
      end

      def configured? : Bool
        !@api_key.nil? && !@user_id.nil?
      end

      def self.config_path : String
        CONFIG_FILE.to_s
      end
    end
  end
end
