"""
Tests for billing management commands.
"""
import pytest
from io import StringIO
from django.core.management import call_command
from django_celery_beat.models import PeriodicTask, CrontabSchedule


@pytest.mark.django_db
class TestSetupBillingTasks:
    """Test the setup_billing_tasks management command."""

    def test_creates_periodic_task(self):
        """Command should create the grace period check task."""
        # Act
        out = StringIO()
        call_command('setup_billing_tasks', stdout=out)

        # Assert
        task = PeriodicTask.objects.get(name='billing-check-grace-periods')
        assert task.task == 'smoothschedule.billing.tasks.check_subscription_grace_periods'
        assert task.enabled is True
        assert task.crontab is not None
        assert task.crontab.hour == '1'
        assert task.crontab.minute == '0'

        output = out.getvalue()
        assert 'Created: billing-check-grace-periods' in output or 'Updated: billing-check-grace-periods' in output
        assert 'Billing tasks set up successfully!' in output

    def test_updates_existing_task(self):
        """Command should update existing task if run twice."""
        # Arrange - create the task first
        call_command('setup_billing_tasks', stdout=StringIO())

        # Act - run again
        out = StringIO()
        call_command('setup_billing_tasks', stdout=out)

        # Assert - should update, not duplicate
        assert PeriodicTask.objects.filter(name='billing-check-grace-periods').count() == 1

        output = out.getvalue()
        assert 'Updated: billing-check-grace-periods' in output

    def test_creates_crontab_schedule(self):
        """Command should create the correct crontab schedule."""
        # Act
        call_command('setup_billing_tasks', stdout=StringIO())

        # Assert
        task = PeriodicTask.objects.get(name='billing-check-grace-periods')
        schedule = task.crontab

        assert schedule.minute == '0'
        assert schedule.hour == '1'
        assert schedule.day_of_week == '*'
        assert schedule.day_of_month == '*'
        assert schedule.month_of_year == '*'
