require "pact_broker/dataset"

module PactBroker
  module Webhooks
    class Execution < Sequel::Model(:webhook_executions)
      # Ignore the columns that were used before the TriggeredWebhook class existed.
      # It used to go Webhook -> Execution, and now it goes Webhook -> TriggeredWebhook -> Execution
      # If we ever release a major version where we drop unused columns, those columns could be deleted.
      EXECUTION_COLUMNS = Sequel::Model.db.schema(:webhook_executions).collect(&:first) - [:webhook_id, :pact_publication_id, :consumer_id, :provider_id]

      set_dataset(Sequel::Model.db[:webhook_executions].select(*EXECUTION_COLUMNS))

      set_primary_key :id
      plugin :timestamps

      associate(:many_to_one, :triggered_webhook, :class => "PactBroker::Webhooks::TriggeredWebhook", :key => :triggered_webhook_id, :primary_key => :id)

      dataset_module(PactBroker::Dataset)

      def <=> other
        comp = created_date <=> other.created_date
        comp = id <=> other.id if comp == 0
        comp
      end
    end
  end
end

# Table: webhook_executions
# Columns:
#  id                   | integer                     | PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY
#  success              | boolean                     | NOT NULL
#  logs                 | text                        |
#  created_at           | timestamp without time zone | NOT NULL
#  triggered_webhook_id | integer                     |
# Indexes:
#  webhook_executions_pkey                       | PRIMARY KEY btree (id)
#  webhook_executions_pact_publication_id_index  | btree (pact_publication_id)
#  webhook_executions_triggered_webhook_id_index | btree (triggered_webhook_id)
# Foreign key constraints:
#  webhook_executions_consumer_id_fkey          | (consumer_id) REFERENCES pacticipants(id)
#  webhook_executions_pact_publication_id_fkey  | (pact_publication_id) REFERENCES pact_publications(id)
#  webhook_executions_provider_id_fkey          | (provider_id) REFERENCES pacticipants(id)
#  webhook_executions_triggered_webhook_id_fkey | (triggered_webhook_id) REFERENCES triggered_webhooks(id)
#  webhook_executions_webhook_id_fkey           | (webhook_id) REFERENCES webhooks(id)
