from datetime import timedelta

from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone

from .models import Event, Registration


class EventFlowTests(TestCase):
    def setUp(self):
        now = timezone.now() + timedelta(days=7)
        self.user = get_user_model().objects.create_user(username='organizer', password='testpass123')

        self.event = Event.objects.create(
            title='Design Systems Lab',
            summary='Hands-on session for collaborative design systems.',
            description='A practical session for teams building consistent digital products.',
            venue='Northstar Studio',
            start_at=now,
            end_at=now + timedelta(hours=2),
            capacity=2,
        )

    def test_home_page_loads_event(self):
        response = self.client.get(reverse('home'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, self.event.title)

    def test_registration_creates_attendee_and_redirects(self):
        response = self.client.post(
            reverse('event_detail', args=[self.event.slug]),
            {
                'full_name': 'Jordan Lee',
                'email': 'jordan@example.com',
                'company': 'Studio North',
                'notes': 'Vegetarian meal',
            },
            follow=True,
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Registration.objects.count(), 1)
        self.assertContains(response, 'Your spot is secured')

    def test_capacity_overflow_goes_to_waitlist(self):
        Registration.objects.create(event=self.event, full_name='One', email='one@example.com')
        Registration.objects.create(event=self.event, full_name='Two', email='two@example.com')
        self.client.post(
            reverse('event_detail', args=[self.event.slug]),
            {
                'full_name': 'Three',
                'email': 'three@example.com',
                'company': '',
                'notes': '',
            },
        )
        self.assertEqual(Registration.objects.get(email='three@example.com').status, Registration.Status.WAITLIST)
    def test_dashboard_requires_login(self):
        response = self.client.get(reverse('organizer_dashboard'))
        self.assertEqual(response.status_code, 302)
        self.assertIn(reverse('login'), response.url)

    def test_logged_in_organizer_can_open_dashboard(self):
        self.client.force_login(self.user)
        response = self.client.get(reverse('organizer_dashboard'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'Organizer dashboard')



    def test_logged_in_organizer_can_create_event_from_dashboard_form(self):
        self.client.force_login(self.user)
        response = self.client.post(
            reverse('organizer_event_create'),
            {
                'title': 'Community Breakfast',
                'summary': 'Meet peers before the keynote.',
                'description': 'A low-key networking breakfast for early arrivals.',
                'venue': 'Northstar Cafe',
                'start_at': (timezone.localtime(self.event.start_at) + timedelta(days=3)).strftime('%Y-%m-%dT%H:%M'),
                'end_at': (timezone.localtime(self.event.end_at) + timedelta(days=3)).strftime('%Y-%m-%dT%H:%M'),
                'capacity': 24,
                'is_published': 'on',
                'registration_opens': '',
                'registration_closes': '',
            },
            follow=True,
        )
        self.assertEqual(response.status_code, 200)
        self.assertTrue(Event.objects.filter(title='Community Breakfast', venue='Northstar Cafe').exists())
        self.assertContains(response, 'created successfully')

    def test_logged_in_organizer_can_edit_event_from_dashboard_form(self):
        self.client.force_login(self.user)
        response = self.client.post(
            reverse('organizer_event_edit', args=[self.event.slug]),
            {
                'title': 'Design Systems Lab Updated',
                'summary': 'Hands-on session for collaborative design systems.',
                'description': 'A practical session for teams building consistent digital products.',
                'venue': 'Northstar Auditorium',
                'start_at': timezone.localtime(self.event.start_at).strftime('%Y-%m-%dT%H:%M'),
                'end_at': timezone.localtime(self.event.end_at).strftime('%Y-%m-%dT%H:%M'),
                'capacity': 40,
                'is_published': 'on',
                'registration_opens': '',
                'registration_closes': '',
            },
            follow=True,
        )
        self.assertEqual(response.status_code, 200)
        self.event.refresh_from_db()
        self.assertEqual(self.event.title, 'Design Systems Lab Updated')
        self.assertEqual(self.event.venue, 'Northstar Auditorium')
        self.assertEqual(self.event.capacity, 40)
        self.assertContains(response, 'updated successfully')
