"""
Documentation du fichier : facturation/management/commands/populate_db.py

Role du fichier :
    Cette commande de gestion Django automatise une operation interne du projet :
    populate db.

Ce module intervient dans :
    - l'initialisation, le controle ou l'alimentation des donnees ;
    - les taches d'administration executees depuis manage.py.
"""

import random
from decimal import Decimal
from django.core.management.base import BaseCommand
from django.utils import timezone
from faker import Faker
from facturation.models import (
    Configuration, PointDeVente, User, Categorie, 
    Produit, StockPointDeVente, Client, MouvementStock
)
from dgi.models import TaxGroup, ItemType, ClientType
from dgi.tax_groups import get_tax_group_name_for_seed

class Command(BaseCommand):
    """Definit la classe command utilisee dans ce module."""

    help = 'Populate database with fake data'

    def handle(self, *args, **kwargs):
        """Execute la commande de gestion."""

        fake = Faker()
        self.stdout.write('Generating fake data...')

        # 0. DGI Utils (TaxGroups, ItemTypes)
        tax_group_a, _ = TaxGroup.objects.get_or_create(
            code="A",
            defaults={'name': get_tax_group_name_for_seed("A"), 'tax': 0},
        )
        tax_group_b, _ = TaxGroup.objects.get_or_create(
            code="B",
            defaults={'name': get_tax_group_name_for_seed("B"), 'tax': 16},
        )
        
        item_type_goods, _ = ItemType.objects.get_or_create(code="GOODS", defaults={'name': "Bien"})
        item_type_serv, _ = ItemType.objects.get_or_create(code="SERVICES", defaults={'name': "Service"})

        client_type_pp, _ = ClientType.objects.get_or_create(code="PP", defaults={'name': "Physique"})
        client_type_pm, _ = ClientType.objects.get_or_create(code="PM", defaults={'name': "Morale"})

        # 1. Configuration
        if not Configuration.objects.exists():
            Configuration.objects.create(
                taux_change=Decimal('2850.00'),
                nom_entreprise="CHRIS MOBILE FAKE",
                adresse="123 Av. Kasa-Vubu, Kinshasa",
                telephone="+243 81 000 0000",
                n_impot="A1234567M",
                rccm="CD/KIN/RCCM/12-B-000",
                id_nat="01-92-N00000Z",
                tva_percent=Decimal('16.00')
            )
            self.stdout.write(self.style.SUCCESS('Configuration created.'))

        # 2. Points de Vente
        pdv_names = ["Magasin Central", "Succursale Victoire", "Succursale Gombe"]
        pdvs = []
        for name in pdv_names:
            p, created = PointDeVente.objects.get_or_create(nom=name, defaults={'adresse': fake.address()})
            pdvs.append(p)
        self.stdout.write(self.style.SUCCESS(f'{len(pdvs)} Points de Vente checked/created.'))

        # 3. Users (Vendeurs)
        for i in range(5):
            username = f"vendeur{i+1}"
            if not User.objects.filter(username=username).exists():
                u = User.objects.create_user(
                    username=username,
                    email=f"{username}@test.com",
                    password="password123",
                    role='VENDEUR',
                )
                u.point_de_vente = random.choice(pdvs)
                u.save()
        self.stdout.write(self.style.SUCCESS('Vendeurs created.'))

        # 4. Categories
        cat_names = ["Téléphones", "Accessoires", "Ordinateurs", "Services"]
        categories = []
        for name in cat_names:
            c, _ = Categorie.objects.get_or_create(nom=name, defaults={'description': fake.text()})
            categories.append(c)

        # 5. Produits
        for i in range(20):
            cat = random.choice(categories)
            nom = f"{cat.nom[:-1]} - {fake.word().capitalize()} {random.randint(10, 99)}"
            sku = f"SKU-{random.randint(1000, 9999)}"
            
            if not Produit.objects.filter(code_sku=sku).exists():
                prod = Produit.objects.create(
                    nom=nom,
                    code_sku=sku,
                    categorie=cat,
                    prix_vente=Decimal(random.randint(10, 1500)),
                    taxgroup=random.choice([tax_group_a, tax_group_b]),
                    typeart=item_type_serv if cat.nom == "Services" else item_type_goods
                )
                
                # Stock initial pour chaque PDV
                for pdv in pdvs:
                    qty = random.randint(0, 50)
                    stock, _ = StockPointDeVente.objects.get_or_create(
                        point_de_vente=pdv,
                        produit=prod,
                        defaults={'quantite': 0}
                    )
                    
                    if qty > 0:
                        MouvementStock.objects.create(
                            stock=stock,
                            type_mouvement='APPROVISIONNEMENT',
                            quantite=qty,
                            description="Stock initial fake",
                            responsable=User.objects.first() # Admin
                        )

        self.stdout.write(self.style.SUCCESS('Produits & Stocks created.'))

        # 6. Clients
        for _ in range(10):
            Client.objects.create(
                nom_complet=fake.name(),
                telephone=fake.phone_number(),
                adresse=fake.address(),
                type_client=random.choice(['PARTICULIER', 'ENTREPRISE']),
                client_type=random.choice([client_type_pp, client_type_pm]),
                nif=str(random.randint(1000000, 9999999)) if random.random() > 0.7 else None
            )
        self.stdout.write(self.style.SUCCESS('Clients created.'))
