from decimal import Decimal
from django.core.management.base import BaseCommand
from django.template.defaultfilters import slugify

from app.models import ProductCategory, Product


class Command(BaseCommand):
    help = "Seed boutique: create 3 categories and 3 products (test data)"

    def handle(self, *args, **options):
        categories_data = [
            {"name": "Matériaux", "slug": "materiaux", "description": "Matériaux de construction sélectionnés.", "order": 1},
            {"name": "Équipements", "slug": "equipements", "description": "Équipements et accessoires techniques.", "order": 2},
            {"name": "Solutions Éco", "slug": "solutions-eco", "description": "Solutions durables et performantes.", "order": 3},
        ]

        created_cats = []
        for c in categories_data:
            cat, created = ProductCategory.objects.get_or_create(
                slug=c["slug"],
                defaults={
                    "name": c["name"],
                    "description": c["description"],
                    "order": c["order"],
                    "is_active": True,
                },
            )
            if not created:
                # Ensure fields are up to date
                cat.name = c["name"]
                cat.description = c["description"]
                cat.order = c["order"]
                cat.is_active = True
                cat.save()
            created_cats.append(cat)
        self.stdout.write(self.style.SUCCESS(f"Categories ensured: {[c.slug for c in created_cats]}"))

        # Map slug -> instance
        cats = {c.slug: c for c in created_cats}

        products_data = [
            {
                "name": "Ciment Premium 50kg",
                "category": cats.get("materiaux"),
                "short": "Ciment haute performance pour béton et maçonnerie.",
                "desc": "<p>Ciment certifié pour travaux structuraux, prise régulière et excellente durabilité.</p>",
                "price": Decimal("6500"),
                "currency": "FCFA",
                "stock": 120,
                "featured": True,
            },
            {
                "name": "Fer à béton Ø12mm",
                "category": cats.get("materiaux"),
                "short": "Barre acier nervurée pour armatures.",
                "desc": "<p>Barres d'acier de haute qualité, conformes aux normes, idéales pour le gros œuvre.</p>",
                "price": Decimal("4500"),
                "currency": "FCFA",
                "stock": 300,
                "featured": True,
            },
            {
                "name": "Kit Solaire 1kW",
                "category": cats.get("solutions-eco"),
                "short": "Solution solaire domestique d'appoint.",
                "desc": "<p>Kit complet (panneaux, onduleur, câblage). Installation et conseil possibles.</p>",
                "price": Decimal("350000"),
                "currency": "FCFA",
                "stock": 10,
                "featured": False,
            },
        ]

        for p in products_data:
            slug = slugify(p["name"])[:220]
            product, created = Product.objects.get_or_create(
                slug=slug,
                defaults={
                    "name": p["name"],
                    "category": p["category"],
                    "short_description": p["short"],
                    "description": p["desc"],
                    "price": p["price"],
                    "currency": p["currency"],
                    "stock": p["stock"],
                    "is_featured": p["featured"],
                    "status": "ACTIVE",
                },
            )
            if not created:
                product.name = p["name"]
                product.category = p["category"]
                product.short_description = p["short"]
                product.description = p["desc"]
                product.price = p["price"]
                product.currency = p["currency"]
                product.stock = p["stock"]
                product.is_featured = p["featured"]
                product.status = "ACTIVE"
                product.save()

        self.stdout.write(self.style.SUCCESS("Seed completed: 3 categories, 3 products."))
