from django.test import TestCase
from rest_framework.test import APIClient
from django.urls import reverse
from .models import Student, Teacher, Project, Banner, StudentCoupon, StudentShowcase, StudentProject
from django.utils import timezone
from datetime import timedelta


class DashboardStatsViewTests(TestCase):
    def setUp(self):
        # Create minimal data
        self.student = Student.objects.create(name='测试学员')
        self.teacher = Teacher.objects.create(name='机构A')
        Project.objects.create(title='项目1', teacher=self.teacher, is_active=True)
        Banner.objects.create(image='http://example.com/a.png', is_active=True)
        StudentShowcase.objects.create(title='展示1', cover_image='http://example.com/c.png', is_active=True)
        # 优惠券在具体用例中创建

    def test_requires_authentication(self):
        client = APIClient()
        url = '/api/dashboard/stats/'
        resp = client.get(url)
        self.assertEqual(resp.status_code, 401)

    def test_returns_basic_stats_with_auth(self):
        # Create valid coupon and assignment
        from .models import Coupon
        coupon = Coupon.objects.create(title='C1', amount='10', unit='元', desc='D', expiry=timezone.now().date())
        StudentCoupon.objects.create(student=self.student, coupon=coupon)

        # Enrollment for trends
        StudentProject.objects.create(student=self.student, project=Project.objects.first())

        client = APIClient()
        token = f"mock_token_{self.student.id}"
        resp = client.get('/api/dashboard/stats/', HTTP_AUTHORIZATION=f'Bearer {token}')
        self.assertEqual(resp.status_code, 200)
        data = resp.json()
        # Panel data checks
        self.assertIn('panel_data', data)
        panel = data['panel_data']
        for key in ['students', 'organizations', 'projects', 'projects_active', 'coupons', 'banners_active', 'showcases_active']:
            self.assertIn(key, panel)
        # Charts existence
        self.assertIn('pie_chart_data', data)
        self.assertIn('coupon_pie_chart_data', data)
        self.assertIn('bar_chart_data', data)
        self.assertIn('line_chart_data', data)

# Create your tests here.
