from django.db import migrations

def sync_trust_accounts_and_payment_modes(apps, schema_editor):
    AccountHead = apps.get_model('accounting', 'AccountHead')
    TrustAccount = apps.get_model('accounting', 'TrustAccount')
    PaymentMode = apps.get_model('accounting', 'PaymentMode')

    # 1. Default Cash mode (no linked account head)
    PaymentMode.objects.get_or_create(
        name='Cash',
        defaults={
            'name_ta': 'ரொக்கம்',
            'is_active': True,
            'account_head': None,
            'trust_account': None
        }
    )

    # 2. Sync all TrustAccounts to have an AccountHead and linked PaymentMode
    for account in TrustAccount.objects.all():
        head = account.account_head
        if not head:
            # Check if an AccountHead with this name already exists
            head = AccountHead.objects.filter(name=account.account_name).first()
            if not head:
                head = AccountHead.objects.create(
                    name=account.account_name,
                    account_type='Asset',
                    head_type='General',
                    is_active=(account.status == 'Active'),
                    created_by=account.created_by
                )
            account.account_head = head
            account.save(update_fields=['account_head'])

        # Ensure PaymentMode exists and is linked
        pm, _ = PaymentMode.objects.get_or_create(
            name=account.account_name,
            defaults={
                'name_ta': '',
                'account_head': head,
                'trust_account': account,
                'is_active': (account.status == 'Active')
            }
        )
        if pm.account_head != head or pm.trust_account != account:
            pm.account_head = head
            pm.trust_account = account
            pm.is_active = (account.status == 'Active')
            pm.save(update_fields=['account_head', 'trust_account', 'is_active'])

    # 3. Ensure other standard payment modes exist
    standard_modes = [
        ('Bank Transfer', 'வங்கி பரிமாற்றம்'),
        ('UPI', 'யுபிஐ (UPI)'),
        ('Cheque', 'காசோலை'),
        ('Credit', 'கடன்'),
        ('Commodities', 'பொருட்கள்'),
    ]
    for mode_name, mode_ta in standard_modes:
        if not PaymentMode.objects.filter(name=mode_name).exists():
            # If there's a matching TrustAccount of type Bank/Commodities, link it
            linked_ta = None
            if mode_name in ['Bank Transfer', 'UPI', 'Cheque']:
                linked_ta = TrustAccount.objects.filter(account_type='Bank', status='Active').first()
            elif mode_name == 'Commodities':
                linked_ta = TrustAccount.objects.filter(account_type='Commodities', status='Active').first()

            PaymentMode.objects.create(
                name=mode_name,
                name_ta=mode_ta,
                account_head=linked_ta.account_head if linked_ta else None,
                trust_account=linked_ta if linked_ta else None,
                is_active=True
            )

def reverse_sync(apps, schema_editor):
    pass

class Migration(migrations.Migration):

    dependencies = [
        ('accounting', '0012_receipt_journal_entry_trustaccount_account_head_and_more'),
    ]

    operations = [
        migrations.RunPython(sync_trust_accounts_and_payment_modes, reverse_sync),
    ]
