require "sequel/plugins/serialization"

module PactBroker
  module Deployments
    class Environment < Sequel::Model
      set_primary_key :id

      OPEN_STRUCT_TO_JSON = lambda { | open_struct | Sequel.object_to_json(open_struct.collect(&:to_h)) }
      JSON_TO_OPEN_STRUCT = lambda { | json | Sequel.parse_json(json).collect{ | hash| OpenStruct.new(hash) } }
      plugin :upsert, identifying_columns: [:uuid]
      plugin :serialization
      plugin :timestamps, update_on_create: true
      serialize_attributes [OPEN_STRUCT_TO_JSON, JSON_TO_OPEN_STRUCT], :contacts

      dataset_module do
        def delete
          PactBroker::Deployments::DeployedVersion.where(environment: self).delete
          PactBroker::Deployments::ReleasedVersion.where(environment: self).delete
          super
        end
      end

      def delete
        PactBroker::Deployments::DeployedVersion.where(environment: self).delete
        PactBroker::Deployments::ReleasedVersion.where(environment: self).delete
        super
      end

      def production?
        production
      end
    end
  end
end

# Table: environments
# Columns:
#  id           | integer                     | PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY
#  uuid         | text                        | NOT NULL
#  name         | text                        | NOT NULL
#  display_name | text                        |
#  production   | boolean                     | NOT NULL
#  contacts     | text                        |
#  created_at   | timestamp without time zone | NOT NULL
#  updated_at   | timestamp without time zone | NOT NULL
# Indexes:
#  environments_pkey       | PRIMARY KEY btree (id)
#  environments_name_index | UNIQUE btree (name)
#  environments_uuid_index | UNIQUE btree (uuid)
# Referenced By:
#  currently_deployed_version_ids | currently_deployed_version_ids_environment_id_fkey | (environment_id) REFERENCES environments(id) ON DELETE CASCADE
#  deployed_versions              | deployed_versions_environment_id_fkey              | (environment_id) REFERENCES environments(id)
#  released_versions              | released_versions_environment_id_fkey              | (environment_id) REFERENCES environments(id)
