"""Role/profile mapping in the EHC importer's ``users`` stage.

Drives ``Command._stage_users`` in isolation by monkeypatching ``_query`` (so no
MariaDB source is needed), covering the investor + admin onboarding fix: legacy
``role_id`` 4 → INVESTOR (+ InvestorProfile shell) and 1 → SME_ADMIN.
"""

import io

from django.contrib.auth import get_user_model
from django.test import TestCase

from apps.core.permissions.roles import UserRole
from apps.smehub.onboarding.management.commands.import_smehub_ehc import Command
from apps.smehub.onboarding.models import InvestorProfile

User = get_user_model()


def _make_cmd(rows):
    """A Command wired with just the state ``_stage_users`` touches."""
    cmd = Command()
    cmd.stdout = io.StringIO()
    cmd.report_rows = []
    cmd.limit = 0
    cmd._user_cache = {}
    cmd._query = lambda *a, **k: rows
    return cmd


def _row(**over):
    base = dict(
        id=1, name="Jane Doe", email="jane@example.com", alias="",
        email_verified_at=None, deleted_at=None, role_id=4,
    )
    base.update(over)
    return base


class StageUsersRoleMappingTests(TestCase):
    def test_investor_gets_role_and_profile_shell(self):
        _make_cmd([_row(id=101, email="inv@example.com", role_id=4)])._stage_users()
        u = User.objects.get(email="inv@example.com")
        self.assertEqual(u.role, UserRole.INVESTOR)
        self.assertTrue(InvestorProfile.objects.filter(user=u).exists())

    def test_admin_maps_to_sme_admin_without_staff(self):
        _make_cmd([_row(id=102, email="adm@example.com", role_id=1)])._stage_users()
        u = User.objects.get(email="adm@example.com")
        self.assertEqual(u.role, UserRole.SME_ADMIN)
        self.assertFalse(u.is_staff)
        self.assertFalse(u.is_superuser)
        self.assertFalse(InvestorProfile.objects.filter(user=u).exists())

    def test_rerun_is_idempotent(self):
        rows = [_row(id=103, email="inv2@example.com", role_id=4)]
        _make_cmd(rows)._stage_users()
        _make_cmd(rows)._stage_users()
        u = User.objects.get(email="inv2@example.com")
        self.assertEqual(u.role, UserRole.INVESTOR)
        self.assertEqual(InvestorProfile.objects.filter(user=u).count(), 1)

    def test_existing_role_not_clobbered(self):
        existing = User.objects.create_user(
            email="ent@example.com", password="x", role=UserRole.ENTREPRENEUR,
        )
        _make_cmd([_row(id=104, email="ent@example.com", role_id=4)])._stage_users()
        existing.refresh_from_db()
        self.assertEqual(existing.role, UserRole.ENTREPRENEUR)
        self.assertFalse(InvestorProfile.objects.filter(user=existing).exists())
