# Generated migration for initial Chart of Accounts
from django.db import migrations
from django.contrib.auth import get_user_model

User = get_user_model()


def create_initial_accounts(apps, schema_editor):
    """
    Create initial Chart of Accounts for microfinance operations.
    
    Account Structure:
    - Assets: Loan Portfolio, Accrued Interest, Cash, Bank accounts
    - Liabilities: Client Savings, Accrued Expenses
    - Equity: Share Capital, Retained Earnings
    - Income: Interest Income, Fee Income
    - Expenses: Operating, Staff, Provisions, Depreciation
    """
    Account = apps.get_model('accounting', 'Account')
    
    # Get the first superuser to set as created_by
    try:
        superuser = User.objects.filter(is_superuser=True).first()
    except:
        superuser = None
    
    # Define all system accounts with their properties
    system_accounts = [
        # ASSET ACCOUNTS
        {
            'code': '202001',
            'name': 'Loan Portfolio',
            'account_type': 'asset',
            'subtype': 'loan_portfolio',
            'description': 'Outstanding principal balance of all active loans',
            'is_system_account': True,
        },
        {
            'code': '202002',
            'name': 'Accrued Interest Receivable',
            'account_type': 'asset',
            'subtype': 'current_asset',
            'description': 'Interest earned but not yet collected on loans',
            'is_system_account': True,
        },
        {
            'code': '202003',
            'name': 'Cash - Main Branch',
            'account_type': 'asset',
            'subtype': 'current_asset',
            'description': 'Cash on hand at main branch',
            'is_system_account': True,
        },
        {
            'code': '202004',
            'name': 'Bank - Main Account',
            'account_type': 'asset',
            'subtype': 'current_asset',
            'description': 'Main bank account for operations',
            'is_system_account': True,
        },
        {
            'code': '202005',
            'name': 'M-Pesa Account',
            'account_type': 'asset',
            'subtype': 'current_asset',
            'description': 'M-Pesa mobile money account',
            'is_system_account': True,
        },
        {
            'code': '202010',
            'name': 'Allowance for Loan Losses',
            'account_type': 'asset',
            'subtype': 'loan_portfolio',
            'description': 'Provision for expected loan defaults (contra-asset)',
            'is_system_account': True,
        },
        
        # LIABILITY ACCOUNTS
        {
            'code': '301001',
            'name': 'Client Savings Deposits',
            'account_type': 'liability',
            'subtype': 'client_savings',
            'description': 'Savings deposits from clients',
            'is_system_account': True,
        },
        {
            'code': '301002',
            'name': 'Accrued Expenses Payable',
            'account_type': 'liability',
            'subtype': 'current_liability',
            'description': 'Expenses incurred but not yet paid',
            'is_system_account': True,
        },
        
        # EQUITY ACCOUNTS
        {
            'code': '350001',
            'name': 'Share Capital',
            'account_type': 'equity',
            'subtype': None,
            'description': 'Capital contributed by shareholders',
            'is_system_account': True,
        },
        {
            'code': '350002',
            'name': 'Retained Earnings',
            'account_type': 'equity',
            'subtype': None,
            'description': 'Accumulated profits retained in the business',
            'is_system_account': True,
        },
        
        # INCOME ACCOUNTS
        {
            'code': '401001',
            'name': 'Interest Income - Loans',
            'account_type': 'income',
            'subtype': None,
            'description': 'Interest earned on loan portfolio',
            'is_system_account': True,
        },
        {
            'code': '401002',
            'name': 'Fee Income',
            'account_type': 'income',
            'subtype': None,
            'description': 'Fees earned from various services',
            'is_system_account': True,
        },
        
        # EXPENSE ACCOUNTS
        {
            'code': '501001',
            'name': 'Operating Expenses',
            'account_type': 'expense',
            'subtype': None,
            'description': 'General operating expenses',
            'is_system_account': True,
        },
        {
            'code': '501002',
            'name': 'Staff Salaries',
            'account_type': 'expense',
            'subtype': None,
            'description': 'Employee salaries and wages',
            'is_system_account': True,
        },
        {
            'code': '501003',
            'name': 'Loan Loss Provision Expense',
            'account_type': 'expense',
            'subtype': None,
            'description': 'Expense for estimated loan losses',
            'is_system_account': True,
        },
        {
            'code': '502001',
            'name': 'Depreciation Expense',
            'account_type': 'expense',
            'subtype': None,
            'description': 'Depreciation of fixed assets',
            'is_system_account': True,
        },
    ]
    
    # Create all accounts
    for account_data in system_accounts:
        Account.objects.create(
            code=account_data['code'],
            name=account_data['name'],
            account_type=account_data['account_type'],
            subtype=account_data['subtype'],
            description=account_data['description'],
            is_system_account=account_data['is_system_account'],
            is_active=True,
            created_by=superuser,
        )


def reverse_initial_accounts(apps, schema_editor):
    """
    Remove all system accounts created by this migration.
    """
    Account = apps.get_model('accounting', 'Account')
    
    # Delete all system accounts by their codes
    system_account_codes = [
        '202001', '202002', '202003', '202004', '202005', '202010',
        '301001', '301002',
        '350001', '350002',
        '401001', '401002',
        '501001', '501002', '501003', '502001',
    ]
    
    Account.objects.filter(code__in=system_account_codes).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('accounting', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(create_initial_accounts, reverse_initial_accounts),
    ]
