from django.conf import settings
from ..typehints import TenantChange


# ---------------------------------------------------------------------------
def confirm_related_policy(company, policy) -> dict:  # type: ignore[no-untyped-def]
    """
    Helper method to compare Company policy to another Record policy.
    """
    # any company can use records with no policy assigned
    if not policy:
        return {}

    if company.policy == policy:
        return {}

    if not company.policy_id:
        return {
            'message': f'Company {company} has no policy assigned; do not assign one here.',
            'code': 'unrelated_policy',
        }

    if company.policy.policy_is_related(policy):
        return {}

    return {
        'message': f'Company {company} is assigned to a policy unrelated to this policy.',
        'code': 'unrelated_policy',
    }


# ----------------------------------------------------------------------
def confirm_legal_tenant_change(tenant_fields: dict[str, TenantChange]) -> dict:
    """
    When an instance has its Tenant fields changed, it may not go from
    being Universal (no Company assigned) to being assigned to a Company or Policy.

    This would mean that the record must be revoked from consoles where
    the new Company or Policy is not present.

    :param tenant_fields: {
            'policy': {
                'old': '9c1f7978-73fa-11ec-8b8c-7085c27cfb9b',
                'new': 'a4aef2db-73fa-11ec-919a-7085c27cfb9b',
            },
            'company': {
                'old': None,
                'new': '9340bd30-73fa-11ec-873c-7085c27cfb9b',
            }
        }
    """

    if not tenant_fields:
        return {}

    # Exit early if any old tenant fields were set - the record wasn't universal
    for tenant_field in settings.TENANT_FIELDS:
        try:
            if tenant_fields[tenant_field]['old']:
                return {}
        except KeyError:
            continue

    old_tenants = []
    new_tenants = []
    changed_tenant_columns = []

    for tenant_field in settings.TENANT_FIELDS:
        if tenant_field not in tenant_fields:
            continue

        values = tenant_fields[tenant_field]
        old_value = values['old']
        new_value = values['new']
        old_tenants.append(old_value)
        new_tenants.append(new_value)

        if old_value != new_value:
            changed_tenant_columns.append(tenant_field)

    # If all old tenants were None, that means the record had been universal
    was_universal = not any(old_tenants)
    tenancy_changed = any(new_tenants)

    if tenancy_changed and was_universal:
        tenant_field = changed_tenant_columns[0]
        return {
            'message': f'Cannot assign Universal record to a {tenant_field.title()}!!',
            'code': 'illegal_tenant',
            'tenant': tenant_field,
        }

    return {}


__all__ = (
    'confirm_related_policy',
    'confirm_legal_tenant_change',
)
