# typed: false
require "rails_helper"

RSpec.describe BlobFile, type: :model do
  describe "basic functionality" do
    it "can be built and saved" do
      content_bytes = SecureRandom.alphanumeric(1024)
      blob_file =
        BlobFile.new(content_bytes: content_bytes, content_type: "text")
      expect(blob_file).to be_valid
      expect(blob_file.size_bytes).to eq(1024)
      expect(blob_file.content_bytes).to eq(content_bytes)
      expect(blob_file.content_type).to eq("text")
      expect(blob_file.content_bytes.encoding).to eq(Encoding::ASCII_8BIT)

      expect(blob_file.save).to be true
    end

    it "counts bytes with unicode characters" do
      content_bytes = "fooばr"
      blob_file =
        BlobFile.new(content_bytes: content_bytes, content_type: "text")
      expect(blob_file).to be_valid
      expect(blob_file.size_bytes).to eq(7)
      expect(blob_file.save).to be true
      sha256 = blob_file.sha256

      blob_file = BlobFile.find(sha256)
      expect(blob_file.content_bytes).to eq(content_bytes)
    end
  end

  describe "file operations" do
    it "puts the file in the right place" do
      content_bytes = SecureRandom.alphanumeric(1024)
      blob_file =
        BlobFile.new(content_bytes: content_bytes, content_type: "text")
      expect(blob_file.save).to be true
      expect(File.exist?(blob_file.absolute_file_path)).to be true
      expect(File.binread(blob_file.absolute_file_path)).to eq(content_bytes)
    end

    it "handles saving when file already exists" do
      content_bytes = SecureRandom.alphanumeric(1024)
      blob_file =
        BlobFile.new(content_bytes: content_bytes, content_type: "text")
      FileUtils.mkdir_p(File.dirname(blob_file.absolute_file_path))
      File.binwrite(blob_file.absolute_file_path, content_bytes)
      expect(blob_file.save).to be true
      expect(blob_file.content_bytes).to eq(content_bytes)
    end
  end

  describe "path segmentation" do
    it "segments paths correctly" do
      test_cases = [
        ["abcd1234", [2], %w[ab abcd1234]],
        ["abcd1234", [4, 2], %w[abcd 12 abcd1234]],
        ["abcd1234", [4, 2, 2], %w[abcd 12 34 abcd1234]],
        ["abcd1234", [2, 2, 1], %w[ab cd 1 abcd1234]],
      ]
      test_cases.each do |sha256_hex, pattern, expected|
        expect(BlobFile.path_segments(pattern, sha256_hex)).to eq(expected)
      end
    end
  end
end
