from django.db import transaction

from apps.accounts.models import RolePageAccess


ADMIN_PAGE_REGISTRY = [
    # Core
    {"key": "admin_dashboard", "label": "Dashboard", "path": "/admin"},
    # Users
    {"key": "admin_users", "label": "Users", "path": "/admin/users"},
    {"key": "admin_vendors", "label": "Vendors", "path": "/admin/vendors"},
    # Vendor Commercials
    {"key": "admin_commercial_dashboard", "label": "Commercial Dashboard", "path": "/admin/commercial-dashboard"},
    {"key": "admin_vendor_contracts", "label": "Vendor Contracts", "path": "/admin/vendor-contracts"},
    {"key": "admin_pricing_mappings", "label": "Pricing Mappings", "path": "/admin/pricing-mappings"},
    # Products & Orders
    {"key": "admin_products", "label": "Products", "path": "/admin/products"},
    {"key": "admin_orders", "label": "Orders", "path": "/admin/orders"},
    # Opportunity Bundles
    {"key": "admin_schemes", "label": "Opportunity Bundles", "path": "/admin/opportunity-bundles"},
    {"key": "admin_scheme_levels", "label": "Bundle Levels", "path": "/admin/opportunity-bundles/levels"},
    {"key": "admin_scheme_distribution", "label": "Bundle Distribution", "path": "/admin/opportunity-bundles/distribution"},
    {"key": "admin_power_stream", "label": "Power Stream", "path": "/admin/opportunity-bundles/power-stream"},
    # Lucky Dip & Ranks
    {"key": "admin_lucky_dip", "label": "Lucky Dip", "path": "/admin/lucky-dip"},
    {"key": "admin_ranks", "label": "Ranks", "path": "/admin/ranks"},
    # Finance
    {"key": "admin_wallets", "label": "Wallets", "path": "/admin/wallets"},
    {"key": "admin_withdrawals", "label": "Withdrawals", "path": "/admin/withdrawals"},
    {"key": "admin_conversion_rules", "label": "Conversion Rules", "path": "/admin/conversion-rules"},
    {"key": "admin_withdrawal_deductions", "label": "Withdrawal Deductions", "path": "/admin/withdrawal-deductions"},
    # Growth & Network
    {"key": "admin_executive_directors", "label": "Executive Directors", "path": "/admin/executive-directors"},
    {"key": "admin_growth_pool", "label": "Growth Pool", "path": "/admin/growth-pool"},
    # Engagement
    {"key": "admin_notifications", "label": "Notifications", "path": "/admin/notifications"},
    {"key": "admin_support_tickets", "label": "Support Tickets", "path": "/admin/support-tickets"},
    # Platform & Access
    {"key": "admin_settings", "label": "Settings", "path": "/admin/settings"},
    {"key": "admin_razorpay_settings", "label": "Razorpay", "path": "/admin/razorpay-settings"},
    {"key": "admin_sms_settings", "label": "SMS Gateways", "path": "/admin/sms-settings"},
    {"key": "admin_email_settings", "label": "Email Settings", "path": "/admin/email-settings"},
    {"key": "admin_whatsapp_settings", "label": "WhatsApp Settings", "path": "/admin/whatsapp-settings"},
    {"key": "admin_whatsapp_sender", "label": "WhatsApp Sender", "path": "/admin/whatsapp-messages"},
    {"key": "admin_qr_config", "label": "QR Config", "path": "/admin/qr-config"},
    {"key": "admin_social_language_settings", "label": "Social & Languages", "path": "/admin/social-language-settings"},
    {"key": "admin_invoice_settings", "label": "Invoice Settings", "path": "/admin/invoice-settings"},
    {"key": "admin_roles", "label": "Roles", "path": "/admin/roles"},
    {"key": "admin_role_mapping", "label": "Role Mapping", "path": "/admin/role-mapping"},
    {"key": "admin_occupations", "label": "Occupations", "path": "/admin/occupations"},
    # Geo & Branches
    {"key": "admin_geo_config", "label": "Geo Config", "path": "/admin/geo-config"},
    {"key": "admin_franchise_management", "label": "Franchise Management", "path": "/admin/franchise-management"},
    {"key": "admin_branches", "label": "Branches", "path": "/admin/branches"},
    {"key": "admin_geo_upload", "label": "Geo Upload", "path": "/admin/geo-upload"},
    {"key": "admin_states", "label": "States", "path": "/admin/states"},
    {"key": "admin_districts", "label": "Districts", "path": "/admin/districts"},
    {"key": "admin_pincodes", "label": "Pincodes", "path": "/admin/pincodes"},
    {"key": "admin_locations", "label": "Locations", "path": "/admin/locations"},
    # Documents
    {"key": "admin_document_types", "label": "Document Types", "path": "/admin/document-types"},
    {"key": "admin_document_upload", "label": "Document Upload", "path": "/admin/document-upload"},
    {"key": "admin_documents", "label": "Documents", "path": "/admin/documents"},
]


def get_page_keys() -> set[str]:
    return {item["key"] for item in ADMIN_PAGE_REGISTRY}


def get_role_access_map() -> dict[str, dict[str, bool]]:
    rows = RolePageAccess.objects.filter(is_allowed=True).values_list('role_code', 'page_key')
    access: dict[str, dict[str, bool]] = {}
    for role_code, page_key in rows:
        role_code = (role_code or '').strip().upper()
        if not role_code:
            continue
        if role_code not in access:
            access[role_code] = {}
        access[role_code][page_key] = True
    return access


@transaction.atomic
def replace_role_access_map(mapping: dict[str, dict[str, bool]]) -> dict[str, dict[str, bool]]:
    valid_page_keys = get_page_keys()

    RolePageAccess.objects.all().delete()
    records: list[RolePageAccess] = []

    for role_code, pages in (mapping or {}).items():
        normalized_role = str(role_code or '').strip().upper()
        if not normalized_role:
            continue

        for page_key, allowed in (pages or {}).items():
            normalized_page = str(page_key or '').strip()
            if normalized_page not in valid_page_keys:
                continue
            if bool(allowed):
                records.append(RolePageAccess(role_code=normalized_role, page_key=normalized_page, is_allowed=True))

    if records:
        RolePageAccess.objects.bulk_create(records)

    return get_role_access_map()
