# typed: false
require "rails_helper"

describe Domain::E621::Job::ScanPostJob do
  let(:http_client_mock) { instance_double("::Scraper::HttpClient") }
  before { Scraper::ClientFactory.http_client_mock = http_client_mock }

  it "scans the post" do
    post = create(:domain_post_e621_post, e621_id: 2_227_914)
    caused_by_entry = create(:http_log_entry)
    log_entries =
      HttpClientMockHelpers.init_http_client_mock(
        http_client_mock,
        [
          {
            uri: "https://e621.net/posts/2227914.json",
            status_code: 200,
            content_type: "application/json; charset=utf-8",
            contents:
              SpecUtil.read_fixture_file("domain/e621/job/posts_2227914.json"),
            caused_by_entry: caused_by_entry,
          },
        ],
      )

    expect(post.file).to be_nil
    described_class.perform_now(
      { post: post, caused_by_entry: caused_by_entry },
    )
    post.reload
    expect(post.state).to eq("ok")
    expect(post.file).not_to be_nil
    expect(post.file.state).to eq("pending")
    expect(post.file.log_entry).to be_nil
    expect(post.file.url_str).to eq(
      "https://static1.e621.net/data/c0/fa/c0fa5293f1d1440c2d3f2c3e027d3c36.jpg",
    )
    expect(post.md5).to eq("c0fa5293f1d1440c2d3f2c3e027d3c36")
    expect(post.tags_array).to match(
      hash_including("general" => array_including("black_nose", "facial_tuft")),
    )

    expect(SpecUtil.enqueued_job_args(Domain::E621::Job::StaticFileJob)).to eq(
      [{ post_file: post.file, caused_by_entry: log_entries[0] }],
    )
  end

  it "handles a post with no file url" do
    post = create(:domain_post_e621_post, e621_id: 5_270_136)
    log_entries =
      HttpClientMockHelpers.init_http_client_mock(
        http_client_mock,
        [
          {
            uri: "https://e621.net/posts/5270136.json",
            status_code: 200,
            content_type: "application/json; charset=utf-8",
            contents:
              SpecUtil.read_fixture_file("domain/e621/job/posts_5270136.json"),
          },
        ],
      )

    expect(post.file).to be_nil
    described_class.perform_now({ post: post })

    post.reload
    expect(post.file.url_str).to eq(
      "https://static1.e621.net/data/d7/72/d7720676ae1dc4c0ff53c1c34ae5c5b0.png",
    )
    expect(post.file.state).to eq("pending")
    expect(post.file.log_entry).to be_nil
    expect(post.md5).to eq("d7720676ae1dc4c0ff53c1c34ae5c5b0")
    expect(post.tags_array).to match(
      hash_including("general" => array_including("anthro", "duo")),
    )

    expect(SpecUtil.enqueued_job_args(Domain::E621::Job::StaticFileJob)).to eq(
      [{ post_file: post.file, caused_by_entry: log_entries[0] }],
    )
  end
end
