"""
Simplified test suite for HRM system basic functionality.

These tests verify that core models can be created and basic operations work.
They avoid complex OneToOne relationships that cause test isolation issues.
"""

from datetime import date
from django.test import TestCase
from django.contrib.auth.models import User
import uuid

from base.models import Company, Department, JobPosition
from employee.models import Employee
from leave.models import LeaveType, CompanyLeaves


def get_unique_id(prefix='test'):
    """Generate a unique identifier for test data."""
    return f'{prefix}_{uuid.uuid4().hex[:8]}'


class CompanyAndDepartmentTests(TestCase):
    """Test basic company and department operations."""

    def test_company_creation(self):
        """Test company can be created."""
        company = Company.objects.create(
            company=f'TestCo {get_unique_id()}',
            hq=True,
            address='123 Main St',
            country='Nigeria',
            state='Lagos',
            city='Lagos',
            zip='100001'
        )
        self.assertIsNotNone(company.id)
        self.assertEqual(company.hq, True)

    def test_department_creation(self):
        """Test department can be created."""
        company = Company.objects.create(
            company=f'TestCo {get_unique_id()}',
            hq=True,
            address='123 Main St',
            country='Nigeria',
            state='Lagos',
            city='Lagos',
            zip='100001'
        )
        
        department = Department.objects.create(
            department=f'TestDept {get_unique_id()}'
        )
        department.company_id.add(company)
        
        self.assertIsNotNone(department.id)
        self.assertTrue(department.company_id.filter(id=company.id).exists())


class JobPositionTests(TestCase):
    """Test job position creation."""

    def test_job_position_creation(self):
        """Test job position can be created with department."""
        company = Company.objects.create(
            company=f'TestCo {get_unique_id()}',
            hq=True,
            address='123 Main St',
            country='Nigeria',
            state='Lagos',
            city='Lagos',
            zip='100001'
        )
        
        department = Department.objects.create(
            department=f'TestDept {get_unique_id()}'
        )
        department.company_id.add(company)
        
        job_position = JobPosition.objects.create(
            job_position=f'Engineer {get_unique_id()}',
            department_id=department
        )
        
        self.assertIsNotNone(job_position.id)
        self.assertEqual(job_position.department_id, department)


class EmployeeTests(TestCase):
    """Test employee creation (without work information)."""

    def test_employee_creation(self):
        """Test employee can be created."""
        uid = get_unique_id('user')
        user = User.objects.create_user(
            username=uid,
            email=f'{uid}@example.com',
            password='testpass123'
        )
        
        eid = get_unique_id('emp')
        employee = Employee.objects.create(
            employee_first_name='John',
            employee_last_name='Doe',
            email=f'{eid}@example.com',
            phone='1234567890',
            employee_user_id=user
        )
        
        self.assertIsNotNone(employee.id)
        self.assertEqual(employee.employee_first_name, 'John')
        self.assertIsNotNone(employee.employee_user_id)

    def test_multiple_employees(self):
        """Test that multiple employees can be created."""
        employees = []
        for i in range(3):
            uid = get_unique_id(f'user{i}')
            user = User.objects.create_user(
                username=uid,
                email=f'{uid}@example.com',
                password='testpass123'
            )
            
            eid = get_unique_id(f'emp{i}')
            employee = Employee.objects.create(
                employee_first_name=f'Employee{i}',
                employee_last_name='Test',
                email=f'{eid}@example.com',
                phone='1234567890',
                employee_user_id=user
            )
            employees.append(employee)
        
        self.assertEqual(len(employees), 3)
        self.assertEqual(Employee.objects.filter(employee_first_name__startswith='Employee').count(), 3)


class LeaveTypeTests(TestCase):
    """Test leave type and company leave operations (without request context)."""

    def test_leave_model_fields(self):
        """Test that LeaveType model has expected fields."""
        # Verify that LeaveType model exists and has expected fields
        from django.db import models as django_models
        
        fields = {f.name: f for f in LeaveType._meta.get_fields()}
        self.assertIn('name', fields)
        self.assertIn('payment', fields)
        self.assertIn('total_days', fields)


class DateCalculationTests(TestCase):
    """Test date calculations used in leave management."""

    def test_leave_duration_calculation(self):
        """Test leave duration calculation."""
        start_date = date(2024, 12, 25)
        end_date = date(2024, 12, 27)
        duration = (end_date - start_date).days + 1
        self.assertEqual(duration, 3)

    def test_leave_balance_check(self):
        """Test leave balance checking logic."""
        available_days = 20
        requested_days = 5
        
        self.assertGreaterEqual(available_days, requested_days)
        remaining = available_days - requested_days
        self.assertEqual(remaining, 15)

    def test_salary_calculations(self):
        """Test basic salary calculations."""
        basic_salary = 250000
        tax_rate = 0.10
        
        tax = basic_salary * tax_rate
        self.assertEqual(tax, 25000)
        
        deductions = 10000
        net_salary = basic_salary - tax - deductions
        self.assertEqual(net_salary, 215000)
