require "db/mongo/models/model_with_provider"
require 'mongoid'

module Devops
  module Model
    class ProviderAccount

      include ::Mongoid::Document
      include ::Mongoid::Timestamps::CreatedInt
      include ::ActiveModel::Validations

      include ModelWithProvider

      store_in collection: 'provider_accounts'

      field :_id, as: :account_name, overwrite: true, type: String
      field :description, type: String
      field :ssh_key, type: String

#      validates_presence_of :account_name, message: "'account_name' is undefined"
      validates_length_of :account_name, maximum: 100
      validates_format_of :account_name, with: /\A[a-z_][a-z0-9_-]{0,99}\z/, message: "invalid account_name"
      validates_uniqueness_of :account_name, on: :create

      validates_length_of :description, maximum: 500

#      validates_presence_of :ssh_key, message: "'ssh_key' is undefined"
      validates_length_of :ssh_key, maximum: 100
      validates_format_of :ssh_key, with: /\A[a-z_][a-z0-9_-]{0,99}\z/, message: "invalid ssh_key"

      def initialize hash
        raise InvalidRecord.new("Parameter 'account_name' is not a string") unless hash["account_name"].is_a?(String)
        raise InvalidRecord.new("Parameter 'ssh_key' is not a string") unless hash["ssh_key"].is_a?(String)
        super(hash)
      end

      def to_hash
        hash = self.attributes.clone
        hash.delete("_type")
        hash["account_name"] = hash.delete("_id")
        hash
      end

    end
  end
end
