"""Unit tests — Spec 043 activation mapper."""

from __future__ import annotations

import importlib.util
import sys
import unittest
from pathlib import Path

API_ROOT = Path(__file__).resolve().parents[1]


def _load(name: str, rel_path: str):
    path = API_ROOT / rel_path
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise ImportError(path)
    mod = importlib.util.module_from_spec(spec)
    sys.modules[name] = mod
    spec.loader.exec_module(mod)
    return mod


mapper = _load("activation_mapper_043", "app/activation_mapper.py")


class TestActivationMapper043(unittest.TestCase):
    def test_derive_openpanel_username(self):
        self.assertEqual(mapper.derive_openpanel_username("ligbox.com.br"), "ligboxx")
        self.assertEqual(mapper.derive_openpanel_username("empresa.com.br"), "empresax")

    def test_normalize_manager_defaults(self):
        profile = mapper.normalize_company_profile(
            {"legal_name": "ACME LTDA", "email_billing": "fin@acme.com"},
            domain="acme.com.br",
        )
        self.assertEqual(profile["manager_email"], "admin@acme.com.br")

    def test_build_activation_preview(self):
        account = {
            "id": 7,
            "domain": "acme.com.br",
            "billing_state": "awaiting_billing_validation",
            "recurrence_active": False,
            "company_profile": {
                "legal_name": "ACME Serviços LTDA",
                "trade_name": "ACME",
                "tax_id": "00000000000191",
                "email_billing": "fin@acme.com",
                "manager_name": "João Silva",
                "manager_email": "admin@acme.com.br",
                "address": {"country": "BR", "city": "São Paulo", "postal_code": "01310-100"},
            },
        }
        preview = mapper.build_activation_preview(account)
        self.assertTrue(preview["can_activate"])
        self.assertEqual(preview["mapped"]["foss_client"]["email"], "admin@acme.com.br")
        self.assertEqual(preview["mapped"]["openpanel"]["plan_name"], "ligbox-mail-business")
        self.assertEqual(preview["mapped"]["odoo_partner"]["ref"], "acme.com.br")


if __name__ == "__main__":
    unittest.main()
