# Generated by Django 4.2.30 on 2026-09-16 13:35

from django.db import migrations

# (codename, name, category, kind) — kind matches Permission.Kind ('ACTION' | 'COLUMN').
PERMISSIONS = [
    ('inventory.manage_categories', 'Manage categories', 'Inventory', 'ACTION'),
    ('inventory.manage_units', 'Manage units', 'Inventory', 'ACTION'),
    ('inventory.manage_parts', 'Manage spare parts', 'Inventory', 'ACTION'),
    ('inventory.manage_stock_movements', 'Manage stock movements', 'Inventory', 'ACTION'),
    ('inventory.finalize_stock_counts', 'Start / finalize stock counts', 'Inventory', 'ACTION'),
    ('columns.spare_parts.buying_price', 'View buying price on spare parts', 'Inventory', 'COLUMN'),
    ('purchases.manage', 'Manage purchases', 'Purchases', 'ACTION'),
    ('sales.process_returns', 'Process sale returns', 'Sales', 'ACTION'),
    ('sales.approve_price_overrides', 'Approve below-minimum-price sales', 'Sales', 'ACTION'),
    ('columns.sales.profit', 'View profit in sales export', 'Sales', 'COLUMN'),
    ('expenses.manage', 'Manage expenses', 'Expenses', 'ACTION'),
    ('users.manage', 'Manage users & roles', 'Users', 'ACTION'),
    ('settings.manage_email_reports', 'Manage scheduled email reports', 'Settings', 'ACTION'),
    ('settings.manage_notifications', 'Manage notification settings', 'Settings', 'ACTION'),
    ('reports.view', 'View reports & dashboard', 'Reports', 'ACTION'),
]

# Codenames the built-in Seller role starts with — matches exactly what a SELLER
# could already do before RBAC existed (view/sell/count stock, nothing manager-gated).
SELLER_CODENAMES = set()


def seed(apps, schema_editor):
    Permission = apps.get_model('accounts', 'Permission')
    Role = apps.get_model('accounts', 'Role')
    User = apps.get_model('accounts', 'User')

    perm_objs = {}
    for codename, name, category, kind in PERMISSIONS:
        perm, _ = Permission.objects.get_or_create(
            codename=codename, defaults={'name': name, 'category': category, 'kind': kind},
        )
        perm_objs[codename] = perm

    manager_role, _ = Role.objects.get_or_create(
        name='Manager', defaults={'description': 'Full access to every module.', 'is_system': True},
    )
    manager_role.permissions.set(perm_objs.values())

    seller_role, _ = Role.objects.get_or_create(
        name='Seller', defaults={'description': 'Point-of-sale access: sell, view stock, count stock.', 'is_system': True},
    )
    seller_role.permissions.set([perm_objs[c] for c in SELLER_CODENAMES])

    # The old 'role' CharField ('MANAGER'/'SELLER') still exists alongside the new
    # 'role_v2' FK at this point in the migration graph — read it directly so
    # every existing user's actual role carries over, not just known seed accounts.
    for user in User.objects.all():
        user.role_v2 = manager_role if user.role == 'MANAGER' else seller_role
        user.save(update_fields=['role_v2'])


def unseed(apps, schema_editor):
    Role = apps.get_model('accounts', 'Role')
    Permission = apps.get_model('accounts', 'Permission')
    Role.objects.filter(name__in=['Manager', 'Seller'], is_system=True).delete()
    Permission.objects.filter(codename__in=[c for c, *_ in PERMISSIONS]).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0003_permission_role_alter_user_role'),
    ]

    operations = [
        migrations.RunPython(seed, unseed),
    ]
