class PostTag < ApplicationRecord
  include Discard::Model

  before_destroy do
    raise ActiveRecord::ReadOnlyRecord, '消さないでください．'
  end

  belongs_to :post
  belongs_to :tag, counter_cache: :post_count
  belongs_to :created_user, class_name: 'User', optional: true
  belongs_to :deleted_user, class_name: 'User', optional: true

  has_many :sections, -> { order(:begin_ms) }, class_name: 'PostTagSection',
                                               foreign_key: [:post_id, :tag_id],
                                               primary_key: [:post_id, :tag_id],
                                               dependent: :delete_all,
                                               inverse_of: :post_tag

  validates :post_id, presence: true
  validates :tag_id, presence: true
  validates :post_id, uniqueness: {
      scope: :tag_id,
      conditions: -> { where(discarded_at: nil) } }

  def discard_by! deleted_user
    return self if discarded?

    transaction do
      update!(discarded_at: Time.current, deleted_user:)
      Tag.where(id: tag_id).update_all('post_count = GREATEST(post_count - 1, 0)')
    end

    self
  end
end
