# frozen_string_literal: true

class PreviewDocumentPageController < ActionController::API
  include ActiveStorage::SetCurrent

  FORMAT = Templates::ProcessDocument::FORMAT

  def show
    result_data =
      ApplicationRecord.signed_id_verifier.verified(params[:signed_key], purpose: :attachment)

    attachment =
      if result_data.is_a?(Array) && result_data.compact_blank.size == 2
        attachment_id, attachment_uuid = result_data

        ActiveStorage::Attachment.find_by(id: attachment_id, uuid: attachment_uuid)
      elsif result_data
        ActiveStorage::Attachment.find_by(uuid: result_data)
      end

    return head :not_found unless attachment

    @template = attachment.record

    preview_image = attachment.preview_images.joins(:blob)
                              .find_by(blob: { filename: ["#{params[:id]}.png", "#{params[:id]}.jpg"] })

    if preview_image
      return redirect_to preview_image.url(time: ActiveStorage::Attachment.service_url_time),
                         allow_other_host: true
    end

    file_path =
      if attachment.service.name == :disk
        ActiveStorage::Blob.service.path_for(attachment.key)
      else
        find_or_create_document_tempfile_path(attachment)
      end

    preview_image =
      Templates::ProcessDocument.generate_pdf_preview_from_file(attachment, file_path, params[:id].to_i)

    redirect_to preview_image.url(time: ActiveStorage::Attachment.service_url_time), allow_other_host: true
  end

  def find_or_create_document_tempfile_path(attachment)
    file_path = "#{Dir.tmpdir}/attachment-#{Digest::SHA1.hexdigest("#{attachment.id}-#{attachment.uuid}")}"

    File.open(file_path, File::RDWR | File::CREAT, 0o644) do |f|
      f.flock(File::LOCK_EX)

      # rubocop:disable Style/ZeroLengthPredicate
      if f.size.zero?
        f.binmode

        f.write(attachment.download)
      end
      # rubocop:enable Style/ZeroLengthPredicate
    end

    file_path
  end
end
