# frozen_string_literal: true

require 'indicina/index'
require 'indicina/logging'

require 'sequel'

module Indicina
  class TestSuite < Sequel::Model
    one_to_many :tests, key: :suite_id

    attr_accessor :date_range

    def storage_folder
      @storage_folder ||= name == 'mweb' ? File.join('mobile-web', '/') : File.join(name.sanitize, '/')
    end

    def experiences
      @experiences ||= tests_dataset.distinct.select(:experience).where(tested_at: date_range).map(&:experience).sort.compact
    end

    def locations
      @locations ||= tests_dataset.distinct.select(:location).where(tested_at: date_range).map(&:location).sort.compact
    end

    def browsers
      @browsers ||= tests_dataset.distinct.select(:browser).where(tested_at: date_range).map(&:browser).sort.compact
    end

    def mobile_browsers
      @mobile_browsers ||= tests_dataset.distinct.select(:mobile_browser).where(tested_at: date_range).map(&:mobile_browser).sort.compact
    end

    def platforms
      @platforms ||= tests_dataset.distinct.select(:platform).where(tested_at: date_range).map(&:platform).sort.compact
    end

    def urls
      @urls ||= tests_dataset.distinct.select(:url).where(tested_at: date_range).map(&:url).sort.compact
    end

    def indexes
      return @indexes if instance_variable_defined?(:@indexes)
      @indexes = []

      experiences.each do |experience|
        platforms.each do |platform|
          if mobile_browsers.count.positive?
            mobile_browsers.each { |browser| @indexes << Index.new(self, platform, experience, mobile_browser: browser, date_range: date_range) }
          else
            browsers.each { |browser| @indexes << Index.new(self, platform, experience, browser: browser, date_range: date_range) }
          end
        end
      end

      @indexes
    end
  end
end