# frozen_string_literal: true

module QualityApp
  MrlChemicalsRequirementSchema = Dry::Schema.Params do
    optional(:id).filled(:integer)
    required(:chemical_id).filled(:integer)
    required(:mrl_requirement_id).filled(:integer)
    required(:percentage_of_eu_level).maybe(:decimal)
    required(:maximum_residue_level).maybe(:decimal)
  end

  MrlChemicalsRequirementInlineSchema = Dry::Schema.Params do
    required(:chemical_id).filled(:integer)
    required(:mrl_requirement_id).filled(:integer)
    required(:column_value).maybe(:decimal)
    required(:capture_as_perc).filled(:bool)
  end

  class MrlChemicalsContextContract < Dry::Validation::Contract
    params do
      required(:chemical_ids).filled(:array, min_size?: 1).each(:integer)
      optional(:cultivar_id).maybe(:integer)
      optional(:cultivar_group_id).maybe(:integer)
      optional(:qa_standards).filled(:array).each(:integer)
      optional(:packed_tm_groups).filled(:array).each(:integer)
      optional(:target_markets).filled(:array).each(:integer)
      optional(:target_customers).filled(:array).each(:integer)
      required(:capture_as_perc).filled(:bool)
    end

    rule(:cultivar_group_id) do
      base.failure 'Please choose either a Cultivar or Cultivar Group' if (value && values[:cultivar_id]) || (value.nil? && values[:cultivar_id].nil?)
    end

    rule(:qa_standards, :packed_tm_groups, :target_markets, :target_customers) do
      base.failure 'Please select any column(s)' if value.nil? && values[:packed_tm_groups].nil? && values[:target_markets].nil? && values[:target_customers].nil?
    end
  end
end
