"""
Documentation du fichier : facturation/management/commands/init_data.py

Role du fichier :
    Cette commande de gestion Django automatise une operation interne du projet :
    init data.

Ce module intervient dans :
    - l'initialisation, le controle ou l'alimentation des donnees ;
    - les taches d'administration executees depuis manage.py.
"""

from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import timezone as dt_timezone
from facturation.models import *
from faker import Faker
import random
import decimal

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('fr_FR')
        
        self.stdout.write('Création des catégories...')

        categories = ['Boissons', 'Alimentation', 'Produits Frais', 'Hygiène', 'Électronique']
        objs_cats = []
        for cat in categories:
            c, _ = Categorie.objects.get_or_create(nom=cat)
            objs_cats.append(c)

        self.stdout.write('Création des Points de Vente...')
        pdvs = []
        for _ in range(3):
            pdv = PointDeVente.objects.create(
                nom=f"Boutique {fake.city()}",
                adresse=fake.address(),
                responsable=fake.name()
            )
            pdvs.append(pdv)

        self.stdout.write('Création des Utilisateurs...')
        # Admin global
        if not User.objects.filter(username='admin_global').exists():
            User.objects.create_superuser('admin_global', 'admin@test.com', 'password123', role='ADMIN')
        
        # Vendeurs
        vendeurs = []
        for pdv in pdvs:
            u = User.objects.create_user(
                username=f"vendeur_{pdv.id}",
                email=f"vendeur{pdv.id}@test.com",
                password='password123',
                role='VENDEUR',
                point_de_vente=pdv
            )
            vendeurs.append(u)

        self.stdout.write('Création des Produits...')
        produits = []
        for _ in range(20):
            p = Produit.objects.create(
                nom=fake.word().capitalize(),
                code_sku=fake.ean13(),
                categorie=random.choice(objs_cats),
                prix_vente=decimal.Decimal(random.randrange(500, 15000))
            )
            produits.append(p)

        self.stdout.write('Initialisation des Stocks...')
        stocks = []
        for pdv in pdvs:
            for prod in produits:
                s = StockPointDeVente.objects.create(
                    point_de_vente=pdv,
                    produit=prod,
                    quantite=random.randint(10, 100),
                    seuil_alerte=5
                )
                stocks.append(s)

        self.stdout.write('Création des Clients...')
        clients = []
        for _ in range(10):
            c = Client.objects.create(
                nom_complet=fake.name(),
                telephone=fake.phone_number(),
                adresse=fake.address(),
                type_client=random.choice(['PARTICULIER', 'ENTREPRISE'])
            )
            clients.append(c)

        self.stdout.write('Génération de Commandes...')
        for _ in range(50):
            vendeur = random.choice(vendeurs)
            pdv = vendeur.point_de_vente
            client = random.choice(clients)
            
            cmd = Commande.objects.create(
                point_de_vente=pdv,
                vendeur=vendeur,
                client=client,
                date_commande=fake.date_time_between(start_date='-30d', end_date='now', tzinfo=dt_timezone.utc)
            )

            # Lignes de commande

            nb_lignes = random.randint(1, 5)
            total = 0
            for _ in range(nb_lignes):
                prod = random.choice(produits)
                qte = random.randint(1, 5)
                prix = prod.prix_vente
                
                LigneCommande.objects.create(
                    commande=cmd,
                    produit=prod,
                    quantite=qte,
                    prix_unitaire=prix, # Prix au moment de la vente
                    sous_total=qte * prix
                )
                total += (qte * prix)

                # Mouvement stock (simplifié sans check stock négatif pour le fake data)
                try:
                    stock = StockPointDeVente.objects.get(point_de_vente=pdv, produit=prod)
                    MouvementStock.objects.create(
                        stock=stock,
                        type_mouvement='VENTE',
                        quantite=-qte,
                        responsable=vendeur,
                        commande_associee=cmd,
                        date_mouvement=cmd.date_commande
                    )
                except:
                    pass

            cmd.montant_total = total
            
            # Paiement aléatoire
            statut = random.choice(['PAYEE', 'PARTIELLE', 'IMPAYEE'])
            if statut == 'PAYEE':
                montant_paye = total
            elif statut == 'PARTIELLE':
                montant_paye = total / 2
            else:
                montant_paye = 0
            
            if montant_paye > 0:
                mode_str = random.choice(['ESPECES', 'MOBILE_MONEY'])
                from facturation.models import ModePaiement
                mode_obj, _ = ModePaiement.objects.get_or_create(code=mode_str, defaults={'designation': mode_str})
                Paiement.objects.create(
                    commande=cmd,
                    montant=montant_paye,
                    mode_paiement=mode_obj,
                    date_paiement=cmd.date_commande
                )
            
            cmd.montant_paye = montant_paye
            cmd.save() # Le save() recalcule le statut

        self.stdout.write(self.style.SUCCESS('Données factices générées avec succès !'))
