require 'rails_helper'
require 'base64'
require 'tempfile'

RSpec.describe PostThumbnailUploadValidator do
  def with_upload bytes, content_type:, filename:
    tempfile = Tempfile.new(['thumbnail-upload', File.extname(filename)])
    tempfile.binmode
    tempfile.write(bytes)
    tempfile.rewind
    upload = ActionDispatch::Http::UploadedFile.new(
        tempfile:,
        filename:,
        type: content_type)
    yield upload
  ensure
    tempfile&.close!
  end

  it 'accepts a raster upload after decoding and rewinds it' do
    gif = Base64.decode64('R0lGODdhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBADs=')

    with_upload(gif, content_type: 'image/gif', filename: 'thumbnail.gif') do |upload|
      expect { described_class.validate!(upload) }.not_to raise_error
      expect(upload.read(6)).to eq('GIF87a')
    end
  end

  it 'rejects SVG content disguised as a raster MIME type' do
    with_upload(
        '<svg width="10" height="10"></svg>',
        content_type: 'image/png',
        filename: 'thumbnail.png') do |upload|
      expect { described_class.validate!(upload) }
          .to raise_error(
              described_class::InvalidUpload,
              'サムネイル画像の形式が不正です．')
    end
  end

  it 'rejects non-raster content disguised as an image' do
    with_upload(
        '%PDF-1.7',
        content_type: 'image/png',
        filename: 'thumbnail.png') do |upload|
      expect { described_class.validate!(upload) }
          .to raise_error(
              described_class::InvalidUpload,
              'サムネイル画像の形式が不正です．')
    end
  end
end
