from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from vendors.models import Vendor
from django.db import transaction


class Command(BaseCommand):
    help = "Create or reset test customers, vendors, and staff accounts"

    def add_arguments(self, parser):
        parser.add_argument(
            "--password",
            type=str,
            required=True,
            help="Password to set for all created or updated test accounts",
        )
        parser.add_argument(
            "--count",
            type=int,
            default=3,
            help="Number of test customers and vendors to create",
        )

    @transaction.atomic
    def handle(self, *args, **options):
        User = get_user_model()
        password = options["password"]
        count = options["count"]

        created_customers = []
        created_vendors = []
        created_staff = []

        for i in range(1, count + 1):
            email = f"customer{i}@example.com"
            user, _ = User.objects.get_or_create(email=email, defaults={"role": User.Role.CUSTOMER, "is_active": True})
            user.set_password(password)
            user.first_name = f"Customer{i}"
            user.last_name = "Test"
            user.role = User.Role.CUSTOMER
            user.is_active = True
            user.save(update_fields=["password", "first_name", "last_name", "role", "is_active"])
            created_customers.append(email)

        for i in range(1, count + 1):
            email = f"vendor{i}@example.com"
            user, _ = User.objects.get_or_create(email=email, defaults={"role": User.Role.CUSTOMER, "is_active": True})
            user.set_password(password)
            user.first_name = f"Vendor{i}"
            user.last_name = "Test"
            user.role = User.Role.CUSTOMER
            user.is_active = True
            user.save(update_fields=["password", "first_name", "last_name", "role", "is_active"])

            store_name = f"Vendor Store {i}"
            vendor, _ = Vendor.objects.get_or_create(
                user=user,
                defaults={
                    "store_name": store_name,
                    "store_description": "Demo vendor store",
                    "business_email": email,
                    "business_phone": f"99900000{i:02d}",
                    "business_name": f"Vendor Business {i}",
                    "business_type": "Sole Proprietorship",
                    "address_line1": "123 Demo Street",
                    "city": "Mumbai",
                    "state": "MH",
                    "country": "India",
                    "postal_code": "400001",
                    "status": "ACTIVE",
                },
            )
            if vendor.status != "ACTIVE":
                vendor.status = "ACTIVE"
                vendor.save(update_fields=["status"])
            created_vendors.append(email)

        staff_roles = [
            (User.Role.ACCOUNTANT, "accountant"),
            (User.Role.SALES_MANAGER, "sales"),
            (User.Role.INVENTORY_MANAGER, "inventory"),
            (User.Role.CUSTOMER_SUPPORT, "support"),
            (User.Role.CONTENT_MANAGER, "content"),
            (User.Role.MARKETING, "marketing"),
        ]
        for role, prefix in staff_roles:
            email = f"{prefix}@example.com"
            user, _ = User.objects.get_or_create(email=email, defaults={"role": role, "is_active": True, "is_staff": True})
            user.set_password(password)
            user.role = role
            user.is_active = True
            user.is_staff = True
            user.first_name = prefix.capitalize()
            user.last_name = "Staff"
            user.save(update_fields=["password", "role", "is_active", "is_staff", "first_name", "last_name"])
            created_staff.append(f"{email} ({role})")

        role_permissions_map = {
            User.Role.ACCOUNTANT: {
                "apps": ["payments", "orders", "vendors", "products"],
                "perms": ["view", "add", "change"],
            },
            User.Role.INVENTORY_MANAGER: {
                "apps": ["products"],
                "perms": ["view", "add", "change"],
            },
            User.Role.SALES_MANAGER: {
                "apps": ["orders"],
                "perms": ["view", "change"],
            },
            User.Role.CUSTOMER_SUPPORT: {
                "apps": ["orders"],
                "perms": ["view", "change"],
            },
            User.Role.CONTENT_MANAGER: {
                "apps": ["products"],
                "perms": ["view", "change"],
            },
            User.Role.MARKETING: {
                "apps": ["products", "orders", "analytics"],
                "perms": ["view"],
            },
        }

        for role, prefix in staff_roles:
            group_name = str(role)
            group, _ = Group.objects.get_or_create(name=group_name)
            config = role_permissions_map.get(role, None)
            if config:
                app_labels = config["apps"]
                needed = config["perms"]
                cts = ContentType.objects.filter(app_label__in=app_labels)
                perms = Permission.objects.filter(content_type__in=cts)
                selected = []
                for p in perms:
                    for base in needed:
                        if p.codename.startswith(base + "_"):
                            selected.append(p.id)
                            break
                if selected:
                    group.permissions.set(Permission.objects.filter(id__in=selected))
            users = get_user_model().objects.filter(role=role, is_staff=True)
            for u in users:
                u.groups.add(group)
                u.save(update_fields=["updated_at"])

        self.stdout.write(self.style.SUCCESS("Test accounts created or updated"))
        self.stdout.write("Password set for all accounts:")
        self.stdout.write(f"{password}")
        self.stdout.write("Customers:")
        for email in created_customers:
            self.stdout.write(f"- {email}")
        self.stdout.write("Vendors:")
        for email in created_vendors:
            self.stdout.write(f"- {email}")
        self.stdout.write("Staff:")
        for entry in created_staff:
            self.stdout.write(f"- {entry}")
