# companies/migrations/0002_seed_default_company.py
"""
DATA MIGRATION: Seeds a 'Default Company' from existing SystemSettings and License/SubscriptionPlan data.
Then assigns every existing business record to that company.
"""

from django.db import migrations
from django.utils.text import slugify


def seed_default_company(apps, schema_editor):
    SystemSettings = apps.get_model('core', 'SystemSettings')
    License = apps.get_model('core', 'License')
    Plan = apps.get_model('companies', 'Plan')
    Company = apps.get_model('companies', 'Company')
    CompanySettings = apps.get_model('companies', 'CompanySettings')

    # ── 1. Read existing system settings ──────────────────────────────────────
    sys = SystemSettings.objects.first()
    biz_name = (sys.business_name if sys else None) or 'Default Company'
    slug = slugify(biz_name) or 'default'

    # ── 2. Read existing license/plan ─────────────────────────────────────────
    lic = None
    old_plan = None
    try:
        lic = License.objects.select_related('plan').first()
        old_plan = lic.plan if lic else None
    except Exception:
        pass

    # ── 3. Create Plan mirroring old SubscriptionPlan ─────────────────────────
    plan = Plan.objects.create(
        name=getattr(old_plan, 'name', 'Starter') or 'Starter',
        price_monthly=0,
        max_products=getattr(old_plan, 'max_products', 0) or 0,
        max_categories=getattr(old_plan, 'max_categories', 0) or 0,
        max_orders_per_day=getattr(old_plan, 'max_orders_per_day', 0) or 0,
        max_staff=getattr(old_plan, 'max_users', 0) or 0,
        max_branches=5 if getattr(old_plan, 'allow_multi_branch', False) else 1,
        feature_pos_terminal_v1=True,
        feature_pos_terminal_v2_grid=getattr(old_plan, 'allow_grid_pos', False),
        feature_barcode_pos=getattr(old_plan, 'allow_barcode_scanner', False),
        feature_bulk_import=getattr(old_plan, 'allow_bulk_import', False),
        feature_export=True,
        feature_profit_loss=getattr(old_plan, 'allow_pnl_report', False),
        feature_audit_logs=getattr(old_plan, 'allow_audit_log', False),
        feature_suspicious_activity=False,
        feature_multi_branch=getattr(old_plan, 'allow_multi_branch', False),
        feature_wholesale_price=getattr(old_plan, 'allow_wholesale_price', False),
        feature_discount=True,
        feature_promo=getattr(old_plan, 'allow_promo_codes', False),
        feature_android_app=getattr(old_plan, 'allow_android_app', False),
        feature_credit_sales=getattr(old_plan, 'allow_credit_sales', True),
        feature_advanced_reports=getattr(old_plan, 'allow_advanced_reports', False),
        is_active=True,
    )

    # ── 4. Create Company ──────────────────────────────────────────────────────
    company = Company.objects.create(
        name=biz_name,
        slug=slug,
        email=getattr(sys, 'business_email', '') or '',
        phone=getattr(sys, 'business_phone', '') or '',
        address=getattr(sys, 'business_address', '') or '',
        plan=plan,
        is_active=True,
        expiry_date=getattr(lic, 'expires_at', None) if lic else None,
    )

    # ── 5. Create CompanySettings ──────────────────────────────────────────────
    CompanySettings.objects.create(
        company=company,
        business_name=biz_name,
        business_address=getattr(sys, 'business_address', '') or '',
        business_phone=getattr(sys, 'business_phone', '') or '',
        business_email=getattr(sys, 'business_email', '') or '',
        currency=getattr(sys, 'currency', 'NGN') or 'NGN',
        currency_symbol=getattr(sys, 'currency_symbol', '₦') or '₦',
        decimal_places=getattr(sys, 'decimal_places', 2) or 2,
        use_comma_separator=getattr(sys, 'use_comma_separator', True),
        vat_rate=getattr(sys, 'vat_rate', 0) or 0,
        pos_interface_mode=getattr(sys, 'pos_interface_mode', 'classic') or 'classic',
        enable_camera_scanner=getattr(sys, 'enable_camera_scanner', False),
        receipt_header=getattr(sys, 'receipt_header', '') or '',
        receipt_footer=getattr(sys, 'receipt_footer', '') or '',
        show_receipt_logo=getattr(sys, 'show_receipt_logo', True),
        primary_color=getattr(sys, 'primary_color', '#667eea') or '#667eea',
        secondary_color=getattr(sys, 'secondary_color', '#764ba2') or '#764ba2',
        accent_color=getattr(sys, 'accent_color', '#f093fb') or '#f093fb',
        show_inventory=getattr(sys, 'show_inventory', True),
        show_receipts=getattr(sys, 'show_receipts', True),
        show_analytics=getattr(sys, 'show_analytics', True),
        show_reports=getattr(sys, 'show_reports', True),
        enable_sms=getattr(sys, 'enable_sms', False),
        enable_email=getattr(sys, 'enable_email', False),
    )

    # ── 6. Assign existing records to Default Company ─────────────────────────
    db = schema_editor.connection.alias

    # Accounts
    apps.get_model('accounts', 'CustomUser').objects.using(db).filter(
        company__isnull=True
    ).exclude(role='superadmin' if hasattr(apps.get_model('accounts', 'CustomUser'), 'role') else 'superadmin').update(company=company)
    apps.get_model('accounts', 'AuditLog').objects.using(db).filter(company__isnull=True).update(company=company)

    # Core
    apps.get_model('core', 'Branch').objects.using(db).filter(company__isnull=True).update(company=company)
    apps.get_model('core', 'PromoCode').objects.using(db).filter(company__isnull=True).update(company=company)

    # Inventory
    apps.get_model('inventory', 'ProductCategory').objects.using(db).filter(company__isnull=True).update(company=company)
    apps.get_model('inventory', 'Product').objects.using(db).filter(company__isnull=True).update(company=company)
    apps.get_model('inventory', 'Supplier').objects.using(db).filter(company__isnull=True).update(company=company)
    apps.get_model('inventory', 'InventoryTransaction').objects.using(db).filter(company__isnull=True).update(company=company)
    apps.get_model('inventory', 'StockAdjustment').objects.using(db).filter(company__isnull=True).update(company=company)

    # Sales
    apps.get_model('sales', 'POSOrder').objects.using(db).filter(company__isnull=True).update(company=company)
    apps.get_model('sales', 'Customer').objects.using(db).filter(company__isnull=True).update(company=company)
    apps.get_model('sales', 'DailySalesSummary').objects.using(db).filter(company__isnull=True).update(company=company)
    apps.get_model('sales', 'CashReconciliation').objects.using(db).filter(company__isnull=True).update(company=company)
    apps.get_model('sales', 'UnusualTransaction').objects.using(db).filter(company__isnull=True).update(company=company)

    # Assign superadmin users: must keep company=None (they are global)
    # All non-superadmin users with company still null → assign to default
    CustomUser = apps.get_model('accounts', 'CustomUser')
    CustomUser.objects.using(db).filter(company__isnull=True, is_superuser=False).update(company=company)


def reverse_migration(apps, schema_editor):
    # On reverse, just delete the default company (cascades clean all FKs)
    Company = apps.get_model('companies', 'Company')
    Plan = apps.get_model('companies', 'Plan')
    Company.objects.all().delete()
    Plan.objects.all().delete()


class Migration(migrations.Migration):

    dependencies = [
        ('companies', '0001_initial'),
        ('accounts', '0005_add_company_fk'),
        ('core', '0015_add_company_fk'),
        ('inventory', '0009_add_company_fk'),
        ('sales', '0013_add_company_fk'),
    ]

    operations = [
        migrations.RunPython(seed_default_company, reverse_migration),
    ]
