"""
Seed the database with a shop, units, currencies, categories, products,
a supplier, a purchase with items, and stock so products are available in inventory.
No customers. Use: python manage.py seed_shop
"""
from decimal import Decimal
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.contrib.auth import get_user_model

from shop_management.models.data.shop import Shop
from shop_management.models.data.utils import Unit, Currency, PaymentStatus
from shop_management.models.data.supplier import Supplier
from shop_management.models.data.product import Category, Product
from shop_management.models.data.purchase import Purchase, PurchaseItem
from shop_management.models.data.stock import Stock


class Command(BaseCommand):
    help = "Seed shop with units, products, inventory (no customers). Run: python manage.py seed_shop"

    def add_arguments(self, parser):
        parser.add_argument(
            "--username",
            type=str,
            default="demo",
            help="Username for the demo shop owner (default: demo)",
        )
        parser.add_argument(
            "--password",
            type=str,
            default="demo123",
            help="Password for the demo user (default: demo123)",
        )
        parser.add_argument(
            "--clear",
            action="store_true",
            help="Delete existing demo shop data before seeding (keeps user)",
        )

    def handle(self, *args, **options):
        User = get_user_model()
        username = options["username"]
        password = options["password"]
        clear = options["clear"]

        # 1. Get or create demo user (staff so they can log in to shop)
        user, created = User.objects.get_or_create(
            username=username,
            defaults={
                "email": f"{username}@example.com",
                "first_name": "Demo",
                "last_name": "User",
                "is_staff": True,
                "is_superuser": True,
            },
        )
        if created:
            user.set_password(password)
            user.save()
            self.stdout.write(self.style.SUCCESS(f"Created user: {username}"))
        else:
            if not user.is_staff:
                user.is_staff = True
                user.save()
            self.stdout.write(f"Using existing user: {username}")

        # 2. Get or create shop
        shop, shop_created = Shop.objects.get_or_create(
            owner=user,
            name="Demo Shop",
            defaults={"description": "Seeded demo shop for testing"},
        )
        if shop_created:
            self.stdout.write(self.style.SUCCESS("Created shop: Demo Shop"))
        else:
            self.stdout.write("Using existing shop: Demo Shop")

        if clear:
            self._clear_shop_data(shop)
            self.stdout.write(self.style.WARNING("Cleared existing shop data."))

        # 3. Currencies (linked to shop)
        currencies = []
        for title, desc in [("AFN", "Afghan Afghani"), ("USD", "US Dollar")]:
            curr, _ = Currency.objects.get_or_create(
                shop=shop, title=title, defaults={"description": desc}
            )
            currencies.append(curr)
        self.stdout.write(f"Currencies: {[c.title for c in currencies]}")

        # 4. Units (linked to shop)
        units_data = [
            ("Piece", "Single item"),
            ("Box", "One box"),
            ("Kg", "Kilogram"),
            ("Liter", "One liter"),
            ("Pack", "One pack"),
        ]
        units = []
        for title, desc in units_data:
            u, _ = Unit.objects.get_or_create(
                shop=shop, title=title, defaults={"description": desc}
            )
            units.append(u)
        self.stdout.write(f"Units: {[u.title for u in units]}")

        # 5. Supplier
        supplier, _ = Supplier.objects.get_or_create(
            shop=shop,
            name="Demo Supplier",
            defaults={
                "email": "supplier@example.com",
                "contact": "+93701234567",
                "address": "Kabul, Afghanistan",
            },
        )
        self.stdout.write(f"Supplier: {supplier.name}")

        # 6. Categories
        categories_data = [
            ("General", "General products"),
            ("Beverages", "Drinks"),
            ("Snacks", "Snacks and chips"),
            ("Dairy", "Dairy products"),
        ]
        categories = []
        for name, desc in categories_data:
            cat, _ = Category.objects.get_or_create(
                shop=shop, name=name, defaults={"description": desc}
            )
            categories.append(cat)
        self.stdout.write(f"Categories: {[c.name for c in categories]}")

        # 7. Products (to sell) - 50 products
        products = []
        product_names = [
            "Rice 5kg", "Cooking Oil 1L", "Tea 500g", "Water 1.5L", "Biscuits", "Chips", "Milk 1L", "Yogurt",
            "Sugar 1kg", "Salt 500g", "Flour 2kg", "Pasta 500g", "Tomato Sauce", "Ketchup", "Mayonnaise", "Mustard",
            "Coffee 200g", "Juice 1L", "Soda 500ml", "Energy Drink", "Chocolate Bar", "Candy Pack", "Cookies", "Cake Mix",
            "Butter 250g", "Cheese 200g", "Eggs 12pcs", "Bread", "Jam 400g", "Honey 500g", "Peanut Butter", "Olive Oil",
            "Vinegar 500ml", "Soy Sauce", "Spices Mix", "Black Pepper", "Garlic Powder", "Onion Powder", "Chili Powder", "Cumin",
            "Noodles 400g", "Cereal 500g", "Oats 1kg", "Beans 500g", "Lentils 1kg", "Chickpeas 500g", "Corn 400g", "Peas 400g",
            "Tuna Can", "Sardines Can"
        ]
        for i, name in enumerate(product_names):
            cat = categories[i % len(categories)]
            p, _ = Product.objects.get_or_create(
                shop=shop,
                name=name,
                defaults={"category": cat, "description": f"{name} product"},
            )
            products.append(p)
        self.stdout.write(f"Products: {len(products)} items")

        # 8. Create a purchase with items and stock (so products appear in inventory)
        currency = currencies[0]  # AFN
        unit = units[0]  # Piece

        purchase = Purchase.objects.create(
            shop=shop,
            supplier=supplier,
            currency=currency,
            purchase_date=timezone.now().date(),
            discount=Decimal("0"),
            received_amount=Decimal("0"),
            status=PaymentStatus.PENDING,
        )

        for i, product in enumerate(products):
            qty = 20 + (i * 5)
            buy_price = Decimal("50") + (i * 10)
            sale_price = buy_price + Decimal("15")
            purchase_item = PurchaseItem.objects.create(
                purchase=purchase,
                product=product,
                unit=unit,
                quantity=qty,
                buy_price=buy_price,
                sale_price=sale_price,
            )
            Stock.objects.create(
                shop=shop,
                purchase_item=purchase_item,
                quantity=qty,
                sale_price=sale_price,
            )

        self.stdout.write(
            self.style.SUCCESS(
                f"Done. Created purchase with {len(products)} items and stock. "
                f"Login with username={username!r} and password={password!r}"
            )
        )

    def _clear_shop_data(self, shop):
        """Remove stock, purchase items, purchases, products, categories, supplier, units, currencies for this shop."""
        from shop_management.models.data.purchase_payment import PurchasePayment

        # Stock
        Stock.objects.filter(shop=shop).delete()
        # Purchase payments then purchase items then purchases
        for p in Purchase.objects.filter(shop=shop):
            PurchasePayment.objects.filter(purchase=p).delete()
        PurchaseItem.objects.filter(purchase__shop=shop).delete()
        Purchase.objects.filter(shop=shop).delete()
        # Products, categories
        Product.objects.filter(shop=shop).delete()
        Category.objects.filter(shop=shop).delete()
        Supplier.objects.filter(shop=shop).delete()
        Unit.objects.filter(shop=shop).delete()
        Currency.objects.filter(shop=shop).delete()
