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

class Command(BaseCommand):
    help = 'Sets up initial permissions for Shipper and Truck Owner groups'

    def handle(self, *args, **options):
        # 1. Get or Create Groups
        shipper_group, _ = Group.objects.get_or_create(name='SHIPPER')
        truck_owner_group, _ = Group.objects.get_or_create(name='TRUCK_OWNER')
        admin_group, _ = Group.objects.get_or_create(name='ADMIN')

        # 2. Define Permissions
        def get_perms(model, actions=['add', 'change', 'delete', 'view']):
            content_type = ContentType.objects.get_for_model(model)
            return Permission.objects.filter(content_type=content_type, codename__in=[f'{action}_{model._meta.model_name}' for action in actions])

        # Shipper Permissions
        shipper_perms = list(get_perms(Shipment))  # all shipment perms
        shipper_perms += list(get_perms(Bid, actions=['view'])) # can only view bids
        shipper_perms += list(get_perms(Message, actions=['add', 'view'])) # can chat
        shipper_perms += list(get_perms(Truck, actions=['view'])) # can view trucks
        
        shipper_group.permissions.set(shipper_perms)

        # Truck Owner Permissions
        truck_owner_perms = list(get_perms(Truck)) # all truck perms
        truck_owner_perms += list(get_perms(Shipment, actions=['view'])) # can only view shipments
        truck_owner_perms += list(get_perms(Bid)) # all bid perms
        truck_owner_perms += list(get_perms(Message, actions=['add', 'view'])) # can chat
        
        truck_owner_group.permissions.set(truck_owner_perms)

        # Admin Permissions (Full access to core models)
        admin_perms = list(get_perms(Shipment))
        admin_perms += list(get_perms(Truck))
        admin_perms += list(get_perms(Bid))
        admin_perms += list(get_perms(Message))
        
        admin_group.permissions.set(admin_perms)

        self.stdout.write(self.style.SUCCESS('Successfully configured permissions for SHIPPER, TRUCK_OWNER, and ADMIN groups.'))
