class EmployeePosition < ApplicationRecord
  audited

  belongs_to :employee
  belongs_to :position

  associations_for namespace: 'EdFi' do |a|
    a.has_one :id, as: :associated, inverse_of: :associated, dependent: :destroy
  end

  delegate :school, to: :employee

  before_destroy :remove_from_ed_fi, if: :ed_fi_id, prepend: true

  validates :start_date, presence: true
  validates :employment_descriptor, presence: true, if: -> { school.ed_fi_system_indiana? }

  scope :within_date_range, ->(date_range) do
    return if date_range.blank?

    where(start_date: date_range)
      .or(where(end_date: date_range))
      .or(where(end_date: nil)
        .or(where('end_date > ?', date_range.last))
        .where('start_date < ?', date_range.first)
      )
  end

  private
    def remove_from_ed_fi
      return if ed_fi_id.school_year_id != school.current_year.id

      resp = EdFi::Indiana::Sandbox::StaffAssignmentAssociationService.new(
        school.current_year.id,
        id: ed_fi_id.number,
        employee: employee
      ).delete
      throw(:abort) unless resp&.code
    end
end
