"""Integration tests: meeting invite emails are batched and marked sent."""

from datetime import timedelta

import pytest
from django.contrib.auth import get_user_model
from django.core import mail
from django.utils import timezone
from rest_framework.test import APIClient

from apps.meetings.models import Meeting, MeetingInvitation

User = get_user_model()


@pytest.fixture
def admin(db):
    return User.objects.create_superuser(email="admin@test.local", password="x")


@pytest.fixture
def client(admin):
    c = APIClient()
    c.force_authenticate(admin)
    return c


@pytest.fixture
def meeting(db):
    start = timezone.now() + timedelta(days=1)
    return Meeting.objects.create(title="Standup", start_time=start,
                                  end_time=start + timedelta(hours=1))


@pytest.mark.django_db
class TestSendInvites:
    @pytest.fixture(autouse=True)
    def eager_locmem(self, settings):
        settings.BACKGROUND_TASKS_EAGER = True
        settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"

    def test_sends_pending_and_marks_sent(self, client, meeting):
        a = MeetingInvitation.objects.create(meeting=meeting, name="A", email="a@x.com")
        b = MeetingInvitation.objects.create(meeting=meeting, name="B", email="b@x.com")

        resp = client.post(f"/api/meetings/{meeting.id}/send-invites/", {}, format="json")
        assert resp.status_code == 200
        assert resp.json() == {"sent": 2}
        assert len(mail.outbox) == 2
        assert {m.to[0] for m in mail.outbox} == {"a@x.com", "b@x.com"}
        assert mail.outbox[0].subject == "Meeting Invitation: Standup"
        a.refresh_from_db(); b.refresh_from_db()
        assert a.sent_at is not None and b.sent_at is not None

    def test_second_call_sends_nothing(self, client, meeting):
        MeetingInvitation.objects.create(meeting=meeting, name="A", email="a@x.com")
        client.post(f"/api/meetings/{meeting.id}/send-invites/", {}, format="json")
        mail.outbox.clear()
        resp = client.post(f"/api/meetings/{meeting.id}/send-invites/", {}, format="json")
        assert resp.json() == {"sent": 0}
        assert mail.outbox == []

    def test_explicit_invitation_ids(self, client, meeting):
        a = MeetingInvitation.objects.create(meeting=meeting, name="A", email="a@x.com")
        MeetingInvitation.objects.create(meeting=meeting, name="B", email="b@x.com")

        resp = client.post(f"/api/meetings/{meeting.id}/send-invites/",
                           {"invitation_ids": [str(a.id)]}, format="json")
        assert resp.json() == {"sent": 1}
        assert len(mail.outbox) == 1
        assert mail.outbox[0].to == ["a@x.com"]
