# ============================================================
# ADDITIVE: "which company is making this request?" for outgoing mail.
#
# A mail sent while a COMPANY user (Company Admin / HR / employee token) is calling the API must leave through
# THAT company's SMTP - even when the address is an outsider's (e.g. a candidate's other e-mail).
# Mails sent by SuperAdmin tokens, public pages or background jobs carry no company, so they keep using the
# platform (settings.py) SMTP - exactly like the company-registration welcome mail.
# The token is verified (signature + expiry) here; nothing is trusted from the request body.
# ============================================================
import contextvars

_company_id = contextvars.ContextVar("hrn_mail_company_id", default=None)    # company_details.company_id (8 chars)


def current_company():
    cid = _company_id.get()
    if not cid:
        return None
    from Company.models import company_details
    return company_details.objects.filter(company_id=cid).first()


def set_company(cid):
    return _company_id.set(cid)


def reset(token):
    _company_id.reset(token)


class CompanyMailContextMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        cid = None
        auth = request.META.get("HTTP_AUTHORIZATION", "")
        if auth[:7].lower() == "bearer ":
            try:
                from rest_framework_simplejwt.tokens import AccessToken
                tok = AccessToken(auth[7:].strip())
                kind = tok.get("type")
                cid = tok.get("user_id") if kind == "company" else tok.get("company_id") if kind == "employee" else None
            except Exception:                                  # noqa: BLE001 - invalid / expired token: no company context
                cid = None
        t = _company_id.set(cid)
        try:
            return self.get_response(request)
        finally:
            _company_id.reset(t)
