from django.core.management.base import BaseCommand
from departments.models import Department
from status.models import Status

class Command(BaseCommand):
    help = 'Loads default department data based on migration 0002.'

    def handle(self, *args, **options):
        # 1. Dependency Check: Ensure Status objects exist
        if not Status.objects.exists():
            self.stdout.write(self.style.ERROR('No Status objects found. Please load status data first.'))
            self.stdout.write(self.style.WARNING('You can likely do this by running: python manage.py load_status'))
            return

        # Get the 'Active' status, which is required for creating a department
        try:
            active_status = Status.objects.get(title='Active', type='department')
        except Status.DoesNotExist:
            self.stdout.write(self.style.ERROR('"Active" status not found. Please ensure basic statuses are loaded.'))
            return

        # 2. Define the list of departments to be loaded
        departments_to_load = [
            ('Computer Science and Engineering', 'CSE'),
            ('Civil Engineering', 'CE'),
            ('Electrical and Electronics Engineering', 'EEE'),
            ('Department of Business Administration', 'DBA'),
        ]

        # 3. Load the data
        self.stdout.write(self.style.SUCCESS('Loading default departments...'))
        count = 0
        for dept_name, dept_code in departments_to_load:
            obj, created = Department.objects.update_or_create(
                department_code=dept_code,
                defaults={
                    'department_name': dept_name,
                    'status': active_status
                }
            )
            if created:
                count += 1
                self.stdout.write(self.style.SUCCESS(f'Successfully created Department: "{obj.department_name}"'))
            else:
                self.stdout.write(self.style.WARNING(f'Department "{obj.department_name}" already exists, and was updated.'))

        self.stdout.write(self.style.SUCCESS(f'Process complete. {count} new departments created.'))
