# frozen_string_literal: true

class ContractTemplate < ApplicationRecord
  include Exploitable
  include Syncable
  include PgSearch

  belongs_to :project
  belongs_to :parent, class_name: 'ContractTemplate', optional: true
  has_many :duplicates, class_name: 'ContractTemplate', foreign_key: 'parent_id'
  has_many :talent_releases, dependent: :restrict_with_error
  has_many :appearance_releases, dependent: :restrict_with_error
  has_many :acquired_media_releases, dependent: :restrict_with_error
  has_many :location_releases, dependent: :restrict_with_error
  has_many :material_releases, dependent: :restrict_with_error
  has_many :medical_releases, dependent: :restrict_with_error

  monetize :fee_cents
  has_rich_text :body
  has_rich_text :guardian_clause

  validates :name, presence: true
  validates :release_type, presence: true
  validates :fee_cents, numericality: {
    greater_than_or_equal_to: 0,
    less_than_or_equal_to: 99_999_999_99
  }

  pg_search_scope :search, {
    against: [:name, :release_type],
    associated_against: {project: [:name]},
    using: {
      tsearch: {any_word: true, prefix: true},
      trigram: {},
      dmetaphone: {any_word: true}
    }
  }

  scope :non_archived, -> { where(archived_at: nil) }
  scope :order_by_name, -> { order(:name) }

  def fee?
    !fee.zero?
  end

  def releases
    public_send("#{release_type}_releases")
  end

  def duplicated?
    parent.present?
  end

  def archived?
    archived_at.present?
  end

  def archive
    update(archived_at: Time.zone.now)
  end
end
