from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType


class Command(BaseCommand):
    help = 'Creates Admin and Work Logger permission groups with pre-assigned permissions'

    def handle(self, *args, **options):
        # --- Admin Group ---
        # Full access to all core business models + user management
        admin_group, created = Group.objects.get_or_create(name='Admin')
        admin_perms = []

        # All core model permissions
        for model in ['project', 'worker', 'team', 'worklog', 'payrollrecord',
                       'loan', 'payrolladjustment', 'expensereceipt', 'expenselineitem']:
            ct = ContentType.objects.filter(app_label='core', model=model).first()
            if ct:
                admin_perms.extend(Permission.objects.filter(content_type=ct))

        # User management permissions
        user_ct = ContentType.objects.filter(app_label='auth', model='user').first()
        if user_ct:
            admin_perms.extend(Permission.objects.filter(content_type=user_ct))

        group_ct = ContentType.objects.filter(app_label='auth', model='group').first()
        if group_ct:
            admin_perms.extend(Permission.objects.filter(content_type=group_ct))

        admin_group.permissions.set(admin_perms)
        status = 'Created' if created else 'Updated'
        self.stdout.write(self.style.SUCCESS(
            f'{status} "Admin" group with {admin_group.permissions.count()} permissions'
        ))

        # --- Work Logger Group ---
        # Can log work, view history, create receipts - restricted to their teams/projects
        supervisor_group, created = Group.objects.get_or_create(name='Work Logger')
        supervisor_codenames = [
            # Projects - view only
            'view_project',
            # Workers - view only
            'view_worker',
            # Teams - view only
            'view_team',
            # Work logs - full access (log attendance, edit, view)
            'add_worklog', 'change_worklog', 'view_worklog',
            # Expense receipts - create and view
            'add_expensereceipt', 'view_expensereceipt',
            # Expense line items - create and view (needed for receipt creation)
            'add_expenselineitem', 'view_expenselineitem',
        ]

        supervisor_perms = Permission.objects.filter(
            content_type__app_label='core',
            codename__in=supervisor_codenames
        )
        supervisor_group.permissions.set(supervisor_perms)
        status = 'Created' if created else 'Updated'
        self.stdout.write(self.style.SUCCESS(
            f'{status} "Work Logger" group with {supervisor_group.permissions.count()} permissions'
        ))

        self.stdout.write('')
        self.stdout.write('To assign a user to a group:')
        self.stdout.write('  1. Go to Admin Panel > Users > select user')
        self.stdout.write('  2. Under "Groups", add them to "Admin" or "Work Logger"')
        self.stdout.write('  3. For Work Loggers, also assign them to Projects/Teams')
