from django.db import migrations

def migrate_stock_to_main_branch(apps, schema_editor):
    Product = apps.get_model('inventory', 'Product')
    BranchStock = apps.get_model('inventory', 'BranchStock')
    Company = apps.get_model('companies', 'Company')
    Branch = apps.get_model('core', 'Branch')

    for company in Company.objects.all():
        # Get or create a main branch for the company
        branch = Branch.objects.filter(company=company).first()
        if not branch:
            branch = Branch.objects.create(
                company=company,
                name=company.settings.business_name if hasattr(company, 'settings') and company.settings else "Main Branch",
                is_active=True
            )

        # Migrate all products that have positive stock but are missing from BranchStock
        products = Product.objects.filter(company=company, stock_quantity__gt=0)
        for p in products:
            # Check if it already exists to be safe
            if not BranchStock.objects.filter(product=p, branch=branch).exists():
                BranchStock.objects.create(
                    company=company,
                    product=p,
                    branch=branch,
                    quantity=p.stock_quantity
                )

def reverse_migrate_stock(apps, schema_editor):
    pass # No reversal necessary as deleting branch stock would ruin data

class Migration(migrations.Migration):
    dependencies = [
        ('inventory', '0012_stockadjustment_branch'),
        ('core', '0001_initial'),
        ('companies', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(migrate_stock_to_main_branch, reverse_migrate_stock),
    ]
