# frozen_string_literal: true

class MatchAppearanceReleasesJob < ApplicationJob
  queue_as :default

  def perform(project, attachments)
    filtered_attachments_object = filter_attachments attachments

    return if filtered_attachments_object[:keys].blank?

    matching_request = MatchingRequest.create project: project, attachments: filtered_attachments_object[:signed_ids]

    payload = { request_id: matching_request.id, bucket: aws_bucket_name, files: filtered_attachments_object[:keys]}
    response = BrayniacAI::QrMatching.create! payload
    matches = response.matches || []
    key_signed_id_hash = Hash[filtered_attachments_object[:keys].zip(filtered_attachments_object[:signed_ids])]
    handle_matches matches, project, key_signed_id_hash
    matching_request.destroy
  end

  private

  def handle_matches(matches, project, key_signed_id_hash)
    matches.each do |match|
      contract_key = Array.wrap(match.contracts).first
      headshot_key = Array.wrap(match.headshots).first
      identifier = match.identifier

      contract = key_signed_id_hash[contract_key]
      headshot = key_signed_id_hash[headshot_key]

      next if contract.nil? && headshot.nil?

      identified_release = identifier.blank? ? nil : AppearanceRelease.find_by(identifier: identifier)
      if identified_release.nil?
        create_release project, contract, headshot, identifier
      else
        update_release identified_release, contract, headshot
      end
    end
  end

  def create_release(project, contract, headshot, identifier)
    random_contract_no = AppearanceRelease.random_contract_number.to_s
    is_incomplete = contract.nil? || headshot.nil?
    params = {
      project: project,
      person_first_name: appearance_first_name(is_incomplete),
      person_last_name: random_contract_no
    }

    params[:person_photo] = headshot unless headshot.nil?
    params[:contract] = contract unless contract.nil?
    params[:identifier] = identifier unless blank?

    return if AppearanceRelease.create(params)

    logger.error "Failed to create AppearanceRelease with params : \r\n#{params}"
  end

  def update_release(release, contract, headshot)
    release.contract = contract unless contract.nil?
    release.person_photo = headshot unless headshot.nil?

    release.save
  end

  def appearance_first_name(incomplete)
    if incomplete
      I18n.t('appearance_releases.shared.incomplete_match')
    else
      I18n.t('appearance_releases.shared.matched_import')
    end
  end

  def aws_bucket_name
    ENV.fetch 'AWS_BUCKET'
  end

  def filter_attachments(attachments)
    filtered_attachments_keys = []
    filtered_attachments_signed_ids = []

    attachments.each do |attachment|
      blob = ActiveStorage::Blob.find_signed attachment
      next if blob.nil?

      extension = blob.filename.extension
      next unless blob.image? || extension == 'pdf'

      filtered_attachments_keys << blob.key
      filtered_attachments_signed_ids << attachment
    end

    {
      keys: filtered_attachments_keys,
      signed_ids: filtered_attachments_signed_ids
    }
  end
end
