defmodule Berrypod.Newsletter.CampaignSendWorkerTest do
  use Berrypod.DataCase, async: true
  use Oban.Testing, repo: Berrypod.Repo

  alias Berrypod.Newsletter
  alias Berrypod.Newsletter.CampaignSendWorker

  import Berrypod.NewsletterFixtures

  describe "perform/1" do
    test "sends campaign to confirmed subscribers" do
      confirmed_subscriber_fixture(email: "a@example.com")
      confirmed_subscriber_fixture(email: "b@example.com")

      campaign = campaign_fixture(subject: "Hello!", body: "Test body {{unsubscribe_url}}")
      {:ok, campaign} = Newsletter.update_campaign(campaign, %{status: "sending"})

      assert :ok = perform_job(CampaignSendWorker, %{campaign_id: campaign.id})

      campaign = Newsletter.get_campaign!(campaign.id)
      assert campaign.status == "sent"
      assert campaign.sent_count == 2
      assert campaign.failed_count == 0
      assert campaign.sent_at != nil
    end

    test "only sends to confirmed subscribers" do
      confirmed_subscriber_fixture(email: "active@example.com")

      # Create an unsubscribed subscriber — should be skipped
      sub = confirmed_subscriber_fixture(email: "unsub@example.com")
      Newsletter.unsubscribe(sub.email)

      campaign = campaign_fixture()
      {:ok, campaign} = Newsletter.update_campaign(campaign, %{status: "sending"})

      assert :ok = perform_job(CampaignSendWorker, %{campaign_id: campaign.id})

      campaign = Newsletter.get_campaign!(campaign.id)
      assert campaign.sent_count == 1
    end

    test "skips campaigns with wrong status" do
      campaign = campaign_fixture()
      {:ok, campaign} = Newsletter.update_campaign(campaign, %{status: "sent"})

      assert :ok = perform_job(CampaignSendWorker, %{campaign_id: campaign.id})
    end
  end
end
