"""Tests for homepage carousel subscription gating."""
from django.test import TestCase
from django.urls import reverse

from accounts.models import User
from companies.models import Company
from seekers.models import SeekerProfile
from subscriptions.management.commands.seed_plans import PLANS
from subscriptions.models import CompanySubscription, SeekerSubscription, SubscriptionPlan


class CarouselSubscriptionTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        for plan_data in PLANS:
            SubscriptionPlan.objects.update_or_create(
                slug=plan_data['slug'],
                defaults={**plan_data, 'is_active': True},
            )

        cls.subscribed_seeker_user = User.objects.create_user(
            username='carousel_plus',
            email='carousel-plus@test.com',
            password='testpass123',
            role=User.Role.SEEKER,
        )
        cls.subscribed_seeker = SeekerProfile.objects.create(
            user=cls.subscribed_seeker_user,
            slug='carousel-plus',
            full_name='Plus Seeker',
            headline='Developer',
            category='IT',
            location='Lusaka',
            is_public=True,
            is_featured=True,
        )
        SeekerSubscription.objects.create(
            user=cls.subscribed_seeker_user,
            plan=SubscriptionPlan.objects.get(slug='seeker-professional-plus'),
            is_active=True,
        )

        cls.free_seeker_user = User.objects.create_user(
            username='carousel_free',
            email='carousel-free@test.com',
            password='testpass123',
            role=User.Role.SEEKER,
        )
        cls.free_seeker = SeekerProfile.objects.create(
            user=cls.free_seeker_user,
            slug='carousel-free',
            full_name='Free Seeker',
            headline='Analyst',
            category='Finance',
            location='Lusaka',
            is_public=True,
            is_featured=True,
        )

        cls.employer_sub = User.objects.create_user(
            username='carousel_employer_sub',
            email='carousel-employer-sub@test.com',
            password='testpass123',
            role=User.Role.COMPANY,
        )
        cls.subscribed_company = Company.objects.create(
            name='Subscribed Co',
            slug='subscribed-co',
            initials='SC',
            industry='Tech',
            location='Lusaka',
            description='Subscribed company',
            owner=cls.employer_sub,
            is_featured=True,
        )
        CompanySubscription.objects.create(
            company=cls.subscribed_company,
            plan=SubscriptionPlan.objects.get(slug='company-starter'),
            is_active=True,
        )

        cls.employer_free = User.objects.create_user(
            username='carousel_employer_free',
            email='carousel-employer-free@test.com',
            password='testpass123',
            role=User.Role.COMPANY,
        )
        cls.unsubscribed_company = Company.objects.create(
            name='Unsubscribed Co',
            slug='unsubscribed-co',
            initials='UC',
            industry='Retail',
            location='Lusaka',
            description='No subscription',
            owner=cls.employer_free,
            is_featured=True,
        )

    def test_homepage_carousel_only_includes_subscribers(self):
        response = self.client.get(reverse('home:index'))
        self.assertEqual(response.status_code, 200)

        featured_seekers = list(response.context['featured_seekers'])
        featured_companies = list(response.context['featured_companies'])

        self.assertIn(self.subscribed_seeker, featured_seekers)
        self.assertNotIn(self.free_seeker, featured_seekers)
        self.assertIn(self.subscribed_company, featured_companies)
        self.assertNotIn(self.unsubscribed_company, featured_companies)

    def test_featured_flag_alone_does_not_qualify_for_carousel(self):
        from subscriptions.carousel import carousel_companies_queryset, carousel_seekers_queryset

        self.free_seeker.is_featured = True
        self.free_seeker.save(update_fields=['is_featured'])
        self.unsubscribed_company.is_featured = True
        self.unsubscribed_company.save(update_fields=['is_featured'])

        self.assertNotIn(self.free_seeker, list(carousel_seekers_queryset()))
        self.assertNotIn(self.unsubscribed_company, list(carousel_companies_queryset()))

    def test_offline_subscribers_excluded_from_carousel(self):
        from subscriptions.carousel import carousel_companies_queryset, carousel_seekers_queryset

        self.subscribed_seeker.is_online = False
        self.subscribed_seeker.save(update_fields=['is_online'])
        self.subscribed_company.is_online = False
        self.subscribed_company.save(update_fields=['is_online'])

        self.assertNotIn(self.subscribed_seeker, list(carousel_seekers_queryset()))
        self.assertNotIn(self.subscribed_company, list(carousel_companies_queryset()))

    def test_carousel_querysets_exclude_expired_subscriptions(self):
        from subscriptions.carousel import carousel_companies_queryset, carousel_seekers_queryset
        from django.utils import timezone
        from datetime import timedelta

        SeekerSubscription.objects.filter(user=self.subscribed_seeker_user).update(
            expires_at=timezone.now() - timedelta(days=1),
        )
        CompanySubscription.objects.filter(company=self.subscribed_company).update(
            expires_at=timezone.now() - timedelta(days=1),
        )

        self.assertNotIn(self.subscribed_seeker, list(carousel_seekers_queryset()))
        self.assertNotIn(self.subscribed_company, list(carousel_companies_queryset()))
