# typed: false
require "rails_helper"

RSpec.describe Domain::User, type: :model do
  describe "#upsert_new_favs" do
    let(:log_entry) { create(:http_log_entry) }

    let(:fa_user) { create(:domain_user_fa_user) }
    let(:e621_user) { create(:domain_user_e621_user) }
    let(:ib_user) { create(:domain_user_ib_user) }

    let(:fa_posts) { 2.times.map { create(:domain_post_fa_post) } }
    let(:e621_posts) { 2.times.map { create(:domain_post_e621_post) } }
    let(:ib_posts) { 2.times.map { create(:domain_post_ib_post) } }

    describe "FA users" do
      it "upserts favs for FA users" do
        expect do
          fa_user.upsert_new_favs(fa_posts.map(&:id), log_entry:)
        end.to change { fa_user.reload.user_post_favs.count }.by(2)

        upf = fa_user.user_post_favs.reload
        expect(upf.map(&:post)).to match_array(fa_posts)
        expect(upf.to_a).to all(be_a(Domain::UserPostFav::FaUserPostFav))
      end

      it "works correctly for FA users with old fav type" do
        Domain::UserPostFav.create!(user: fa_user, post: fa_posts.first)
        expect(fa_user.user_post_favs.length).to eq(1)
        expect(fa_user.user_post_favs.first).to be_a(Domain::UserPostFav)

        expect do
          fa_user.upsert_new_favs(fa_posts.map(&:id), log_entry:)
          # binding.pry
        end.to change { fa_user.reload.user_post_favs.length }.by(1)

        expect(fa_user.user_post_favs.length).to eq(2)
        expect(fa_user.user_post_favs.to_a).to all(
          be_a(Domain::UserPostFav::FaUserPostFav),
        )
      end
    end

    describe "E621 users" do
      it "upserts favs for E621 users" do
        expect do
          e621_user.upsert_new_favs(e621_posts.map(&:id), log_entry:)
        end.to change { e621_user.reload.user_post_favs.count }.by(2)

        upf = e621_user.user_post_favs.reload
        expect(upf.map(&:post)).to match_array(e621_posts)
        expect(upf.to_a).to all(be_a(Domain::UserPostFav))
      end

      it "has the right type" do
        e621_user.upsert_new_favs(e621_posts.map(&:id), log_entry:)
        expect(e621_user.reload.user_post_favs.to_a).to all(
          be_a(Domain::UserPostFav),
        )
      end
    end
  end
end
