# frozen_string_literal: true

class ContractTemplate < ApplicationRecord
  include Exploitable
  include Syncable
  include PgSearch

  NUMBER_OF_CUSTOM_FIELDS = 15

  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
  has_many :misc_releases, dependent: :restrict_with_error

  monetize :fee_cents
  has_rich_text :body
  has_rich_text :guardian_clause
  has_rich_text :signature_legal_text

  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) }

  enum accessibility: [:public_template, :private_template]

  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

  def has_questionnaire?
    (1..NUMBER_OF_CUSTOM_FIELDS).any? { |n| public_send("question_#{n}_text").presence }
  end

  def editable?
    releases.size.zero?
  end

  def attributes
    result = super()
    result[:signature_legal_text] = signature_legal_text.as_json
    result
  end
end
