class EdFi::Log < ApplicationRecord
  ENDPOINT_MAPPING = {
    attendance: [:studentschoolattendanceevents],
    calendar: [:calendars, :calendardates],
    master: [:gradingperiods, :sessions],
    parent: [:parents, :studentparentassociations],
    program: [
      :studentprogramassociations,
      :studentspecialeducationprogramassociations,
      :studentcurricularmaterialprogramassociations,
      :studentparentassociations,
      :parents
    ],
    staff: [
      :staffs,
      :staffeducationorganizationemploymentassociations,
      :staffeducationorganizationassignmentassociations,
      :staffeducationorganizationcontactassociations
    ],
    student: [
      :studentschoolassociations,
      :students,
      :studenteducationorganizationassociations
    ],
    course: [:courseofferings, :sections],
    class_roster: [:staffsectionassociations, :studentsectionassociations],
    transcript: [:studentacademicrecords, :coursetranscripts],
    membership: [:studenteducationorganizationresponsibilityassociations],
    accommodation: [:studenteducationorganizationassessmentassociations],
    graduation_plan: [:studentschoolgraduationplans]
  }

  belongs_to :associated, polymorphic: true
  belongs_to :school_year
  
  has_one :school, through: :school_year

  has_one :school, through: :school_year

  scope :ordered, -> { order(:created_at) }
  scope :by_school_year, ->(school_year) { where(school_year_id: school_year) }

  scope :by_endpoints, ->(types) do
    return if types.blank?

    endpoints = types.map { |t| ENDPOINT_MAPPING[t.to_sym] }.flatten
    where(endpoint: endpoints)
  end

  def message
    if school.indiana_environment_service == 'EdFi::Indiana::V2026'
      if JSON.parse(response)['validationErrors']
        message = ''
        JSON.parse(response)['validationErrors'].each do |key, value|
          message += "#{key}: #{value}"
        end
        #remove $. only at the start of the string
        message.gsub(/^\$./, '')
      else
        JSON.parse(response)['errors']
      end
    else
      JSON.parse(response)['message']
    end
  end
end
