from django.core.management.base import BaseCommand
from core.models import Employee, Department, Shift, DailyAttendance, LeaveType, LeaveRequest
from django.utils import timezone
import datetime

class Command(BaseCommand):
    help = 'Populates the database with demo data'

    def handle(self, *args, **options):
        # 1. Create Department
        dept, _ = Department.objects.get_or_create(name='IT Department', code='IT', defaults={'description': 'Information Technology'})
        
        # 2. Create Shift
        shift, _ = Shift.objects.get_or_create(
            name='General Shift', 
            defaults={'start_time': datetime.time(9, 0), 'end_time': datetime.time(17, 0)}
        )
        
        # 3. Create Employees
        emp1, _ = Employee.objects.get_or_create(
            employee_id='EMP001',
            defaults={
                'first_name': 'John',
                'last_name': 'Doe',
                'department': dept,
                'shift': shift,
                'position': 'Software Engineer',
                'joined_date': datetime.date(2023, 1, 1),
                'is_active': True
            }
        )
        
        emp2, _ = Employee.objects.get_or_create(
            employee_id='EMP002',
            defaults={
                'first_name': 'Jane',
                'last_name': 'Smith',
                'department': dept,
                'shift': shift,
                'position': 'Product Manager',
                'joined_date': datetime.date(2023, 2, 1),
                'is_active': True
            }
        )
        
        # 4. Create Leave Types
        lt, _ = LeaveType.objects.get_or_create(name='Sick Leave', defaults={'total_days': 12, 'color_code': '#e74c3c'})
        
        # 5. Create Daily Attendance for today
        today = timezone.now().date()
        DailyAttendance.objects.get_or_create(
            employee=emp1,
            date=today,
            defaults={
                'check_in': datetime.time(9, 5),
                'status': 'present',
                'worked_hours': 8.0
            }
        )
        
        DailyAttendance.objects.get_or_create(
            employee=emp2,
            date=today,
            defaults={
                'check_in': datetime.time(9, 45),
                'status': 'late',
                'is_late': True,
                'worked_hours': 7.25
            }
        )
        
        # 6. Create Pending Leave
        LeaveRequest.objects.get_or_create(
            employee=emp1,
            leave_type=lt,
            start_date=today + datetime.timedelta(days=5),
            end_date=today + datetime.timedelta(days=7),
            defaults={'reason': 'Medical checkup', 'status': 'pending'}
        )

        self.stdout.write(self.style.SUCCESS('Successfully populated demo data.'))
