from django.core.management.base import BaseCommand, CommandError

from accounts.models import User
from app.config import settings
from integrations.models import Client, ClientBranch, ClientUserMembership


class Command(BaseCommand):
    help = "Create a demo client with 3 branches and enable demo data mode."

    def add_arguments(self, parser):
        parser.add_argument("--name", required=True, help="Client display name")
        parser.add_argument("--slug", required=True, help="Client slug")
        parser.add_argument("--subdomain", required=True, help="Client subdomain")
        parser.add_argument(
            "--user-email",
            action="append",
            dest="user_emails",
            default=[],
            help="User email to grant membership (repeatable).",
        )

    def handle(self, *args, **options):
        slug = (options["slug"] or "").strip().lower()
        subdomain = (options["subdomain"] or "").strip().lower()
        name = (options["name"] or "").strip()
        if not slug or not subdomain or not name:
            raise CommandError("name, slug, and subdomain are required")
        client, created = Client.objects.get_or_create(
            slug=slug,
            defaults={
                "name": name,
                "subdomain": subdomain,
                "use_demo_data": True,
                "is_active": True,
            },
        )
        if not created:
            client.name = name
            client.subdomain = subdomain
            client.use_demo_data = True
            client.is_active = True
            client.save(update_fields=["name", "subdomain", "use_demo_data", "is_active", "updated_at"])

        for branch_id, branch in settings.BRANCHES.items():
            ClientBranch.objects.get_or_create(
                client=client,
                branch_id=branch_id,
                defaults={
                    "branch_name": branch.get("name", branch_id),
                    "simpro_api_url": "",
                    "simpro_api_key": "",
                    "xero_enabled": False,
                    "xero_tenant_id": "",
                    "xero_tracking_category_name": "Business Groups",
                    "xero_department_to_option": {},
                    "xero_department_to_company_id": {},
                },
            )

        attached = 0
        for email in options["user_emails"]:
            user = User.objects.filter(username=email.strip().lower()).first()
            if not user:
                self.stdout.write(self.style.WARNING(f"User not found: {email}"))
                continue
            ClientUserMembership.objects.update_or_create(
                client=client,
                user=user,
                defaults={"is_active": True},
            )
            attached += 1

        self.stdout.write(
            self.style.SUCCESS(
                f"Demo client ready: {client.slug} ({client.subdomain}) | branches={client.branches.count()} | memberships_added={attached}"
            )
        )
