from django.db import migrations, models
import django.db.models.deletion


def backfill_shipment_salesitem_merchant(apps, schema_editor):
    """
    为历史数据补齐 merchant（本项目当前声称未上线，但迁移要可重复执行且安全）。
    - Shipment.merchant: 从 customer.merchant 推导
    - SalesItem.merchant:
        - 优先从 shipment.merchant 推导
        - 否则从 created_by.employee.merchant 推导（如果存在）
    """
    Shipment = apps.get_model('shipment', 'Shipment')
    SalesItem = apps.get_model('shipment', 'SalesItem')

    # Shipment: merchant = customer.merchant
    for s in Shipment.objects.filter(merchant__isnull=True).select_related('customer'):
        if s.customer_id:
            s.merchant_id = s.customer.merchant_id
            s.save(update_fields=['merchant'])

    # SalesItem: merchant = shipment.merchant else created_by.employee.merchant
    # 注意：迁移态下 employee 关系可能不存在，需 try/except
    for item in SalesItem.objects.filter(merchant__isnull=True).select_related('shipment', 'shipment__merchant', 'created_by'):
        if item.shipment_id and getattr(item.shipment, 'merchant_id', None):
            item.merchant_id = item.shipment.merchant_id
            item.save(update_fields=['merchant'])
            continue

        user = getattr(item, 'created_by', None)
        emp = getattr(user, 'employee', None) if user else None
        merchant_id = getattr(emp, 'merchant_id', None) if emp else None
        if merchant_id:
            item.merchant_id = merchant_id
            item.save(update_fields=['merchant'])


class Migration(migrations.Migration):

    dependencies = [
        ('basic_info', '0013_alter_customer_options'),
        ('shipment', '0005_fix_shipment_external_finished_product_relation'),
    ]

    operations = [
        migrations.AddField(
            model_name='shipment',
            name='merchant',
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.PROTECT,
                related_name='shipments',
                to='basic_info.merchant',
                verbose_name='所属商户',
            ),
        ),
        migrations.AddField(
            model_name='salesitem',
            name='merchant',
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.PROTECT,
                related_name='sales_items',
                to='basic_info.merchant',
                verbose_name='所属商户',
            ),
        ),
        migrations.RunPython(backfill_shipment_salesitem_merchant, migrations.RunPython.noop),
        migrations.AlterField(
            model_name='shipment',
            name='merchant',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.PROTECT,
                related_name='shipments',
                to='basic_info.merchant',
                verbose_name='所属商户',
            ),
        ),
        migrations.AlterField(
            model_name='salesitem',
            name='merchant',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.PROTECT,
                related_name='sales_items',
                to='basic_info.merchant',
                verbose_name='所属商户',
            ),
        ),
    ]

