from django.test import TestCase, RequestFactory
from django.urls import reverse
from django.contrib.auth.models import User
from userapp.models import CostumUser
from .models import Employee, Contract, Nationality, Profession, Customer
from django.core.files.uploadedfile import SimpleUploadedFile
import json
from .views import getEmployees

class EmployeeViewTest(TestCase):
    def setUp(self):
        # Create test user
        self.factory = RequestFactory()
        self.user = User.objects.create_user(
            username='testuser', 
            email='test@example.com', 
            password='testpassword',
            first_name='Test',
            last_name='User'
        )
        
        # Create customer
        self.customer = Customer.objects.create(
            name="Test Company",
            phone="123456789",
            email="company@test.com",
            ninea="12345",
            rccm="12345",
            address="Test Address"
        )
        
        # Create CostumUser with CUSTOMER_DRH type
        self.cuser = CostumUser.objects.create(
            user=self.user,
            type="CUSTOMER_DRH",
            customer=self.customer
        )
        
        # Create necessary objects for tests
        self.nationality = Nationality.objects.create(name="Test Nationality", code="TN")
        self.profession = Profession.objects.create(name="Test Profession")
        
        # Create a contract
        self.contract = Contract.objects.create(
            customer=self.customer,
            startDate="2025-01-01",
            period=12
        )
        
        # Create test PDF file
        pdf_content = b'%PDF-1.4\n1 0 obj\n<<\n/Type /Catalog\n/Pages 2 0 R\n>>\nendobj\n2 0 obj\n<<\n/Type /Pages\n/Kids [3 0 R]\n/Count 1\n>>\nendobj\n3 0 obj\n<<\n/Type /Page\n/Parent 2 0 R\n/Resources <<\n/Font <<\n/F1 4 0 R\n>>\n>>\n/MediaBox [0 0 612 792]\n/Contents 5 0 R\n>>\nendobj\n4 0 obj\n<<\n/Type /Font\n/Subtype /Type1\n/BaseFont /Helvetica\n>>\nendobj\n5 0 obj\n<<\n/Length 44\n>>\nstream\nBT\n/F1 24 Tf\n100 700 Td\n(Test PDF) Tj\nET\nendstream\nendobj\nxref\n0 6\n0000000000 65535 f\n0000000009 00000 n\n0000000058 00000 n\n0000000115 00000 n\n0000000234 00000 n\n0000000302 00000 n\ntrailer\n<<\n/Size 6\n/Root 1 0 R\n>>\nstartxref\n396\n%%EOF\n'
        self.pdf_file = SimpleUploadedFile("test.pdf", pdf_content, content_type="application/pdf")
        
        # Create an employee
        self.employee_user = User.objects.create_user(
            username='employee', 
            email='employee@example.com',
            password='password',
            first_name='Employee',
            last_name='Test'
        )
        
        self.employee_cuser = CostumUser.objects.create(
            user=self.employee_user,
            type="EMPLOYEE",
            customer=self.customer
        )
        
        self.employee = Employee.objects.create(
            cuser=self.employee_cuser,
            sex="MALE",
            birthdate="1990-01-01",
            phone="987654321",
            address="Employee Address",
            identityNumber="ID12345",
            identityType="CNI",
            profession=self.profession,
            nationality=self.nationality,
            contract=self.contract,
            contractFile=self.pdf_file,
            state="SUBMITTED"
        )

    def test_employee_list_view(self):
        """Test that employees are properly displayed"""
        request = self.factory.post(
            reverse('app:getEmployees'),
            {'start': 0, 'length': 10, 'search[value]': ''}
        )
        request.user = self.user
        request.user.cuser = self.cuser
        
        response = getEmployees(request)
        self.assertEqual(response.status_code, 200)
        
        data = json.loads(response.content)
        self.assertEqual(data['recordsTotal'], 1)
        
        # Check employee data is in response
        employee_data = data['data'][0]
        self.assertEqual(employee_data['name'], 'Employee Test')
        self.assertEqual(employee_data['email'], 'employee@example.com')
        self.assertEqual(employee_data['phone'], '987654321')
        
        # Check PDF button is present for SUBMITTED state
        self.assertIn('mdi-file-pdf-box', employee_data['actions'])
        
    def test_employee_filter_by_state(self):
        """Test employee filtering by state"""
        # Change employee state to test filtering
        self.employee.state = "INITIAL"
        self.employee.save()
        
        request = self.factory.post(
            reverse('app:getEmployees'),
            {'start': 0, 'length': 10, 'search[value]': ''}
        )
        request.user = self.user
        request.user.cuser = self.cuser
        
        response = getEmployees(request)
        data = json.loads(response.content)
        
        # Check warning tag for INITIAL state
        self.assertIn('tag is-warning', data['data'][0]['state'])
        
        # Check that the submit button is not shown for CUSTOMER_DRH users
        # when employee is in INITIAL state
        self.assertNotIn('Soumettre employé', data['data'][0]['actions'])
