class OneRoster::Controller < ActionController::API
  include OneRoster::Doorkeeper::AuthorizeScopes
  include OneRoster::ResponseMethods
  include OneRoster::EncodingMethods
  include OneRoster::ParseMethods
  include OneRoster::OrgScoped

  rescue_from ActiveRecord::RecordNotFound, with: :not_found_response
  rescue_from OneRoster::ErrorHandler::BadRequest, with: :error_response

  private
    def site_url
      @site_url ||= 'https://sycamore.school/ims/oneroster/v1p1'
    end

    def current_school
      @current_school ||= oauth_application.owner
    end

    def oauth_application
      @oauth_application ||= doorkeeper_token.application
    end

    def validate_school_id
      return unless params.key?('school_id') || controller_name.to_sym == :schools

      encoded_id = controller_name.to_sym == :schools ? params[:id] : params[:school_id]
      school = School.find(decode_source_id(encoded_id)['id'])
      return if school.id == current_school.id

      render_error :forbidden
    end

    def current_school_year
      @current_school_year ||= current_school.school_years.current
    end

    def enrollment_school_year
      current_school.admission_config&.school_year || current_school_year
    end

    def resource_active?(first, last)
      Time.zone.today.between?(first, last)
    end

    def bad_request!(code_minor, description=nil)
      raise OneRoster::ErrorHandler::BadRequest.new(code_minor, description)
    end
end
