# ============================================================
# ADDITIVE: Company-aware Django email backend.
#
# Every existing  send_mail(...) / EmailMessage.send()  in the project (recruitment, offers, interviews, transfers ...)
# keeps working unchanged.  This backend looks at WHO the mail is for:
#   * recipient is an employee / candidate of a company that has an enabled SMTP configuration
#         -> sent through THAT company's SMTP account (From / Reply-To are set to the company's address)
#   * the company has NO enabled SMTP  -> the mail is NOT sent (logged as FAILED). The platform / SuperAdmin mailbox
#                                          is never used for company mail (unless COMPANY_MAIL_ALLOW_PLATFORM_FALLBACK=True)
#   * mails of a COMPANY user to any outside address use that company's SMTP too (see mail_context.py)
#   * platform mails (SuperAdmin: company registration, staff logins ...) and public pages
#         -> sent through the previous global backend (settings.COMPANY_MAIL_FALLBACK_BACKEND)
# Every delivery to an employee / candidate is written to CompanyEmailLog (no mail body is stored).
# ============================================================
from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend
from django.utils.module_loading import import_string

SELF = "People.mail_backend.CompanyAwareEmailBackend"


class CompanyAwareEmailBackend(BaseEmailBackend):
    def __init__(self, fail_silently=False, **kwargs):
        super().__init__(fail_silently=fail_silently, **kwargs)
        self._kwargs = kwargs

    def _fallback(self):
        path = getattr(settings, "COMPANY_MAIL_FALLBACK_BACKEND", None) or "django.core.mail.backends.smtp.EmailBackend"
        if path == SELF:                                        # never recurse
            path = "django.core.mail.backends.smtp.EmailBackend"
        return import_string(path)(fail_silently=self.fail_silently, **self._kwargs)

    def send_messages(self, email_messages):
        from . import mail_engine as me
        if not email_messages:
            return 0
        sent, conns, batch, fallback = 0, {}, me.new_batch(), None
        try:
            for msg in email_messages:
                routes = me.route_message(msg)
                if not routes:
                    continue
                whole, all_ok = len(routes) == 1, True
                for r in routes:
                    if r.blocked:                                # company person, but the company has no SMTP configured
                        me.write_logs(r, msg, "FAILED", "NONE", r.reason, batch)
                        all_ok = False
                        if not self.fail_silently:
                            raise me.MailConfigError(r.reason)
                        continue
                    if r.cfg is not None:
                        all_ok = me.deliver_via_company(r, msg, whole, conns, batch, self.fail_silently) and all_ok
                        continue
                    fallback = fallback or self._fallback()
                    part = me.part_for(msg, r, whole)
                    try:
                        ok = bool(fallback.send_messages([part]))
                        me.write_logs(r, msg, "SENT" if ok else "FAILED", "GLOBAL_FALLBACK", "" if ok else "Not accepted by the server.", batch)
                    except Exception as exc:                    # noqa: BLE001
                        me.write_logs(r, msg, "FAILED", "GLOBAL_FALLBACK", me.friendly_error(exc), batch)
                        if not self.fail_silently:
                            raise
                        ok = False
                    all_ok = all_ok and ok
                if all_ok:
                    sent += 1
        finally:
            for c in conns.values():
                try:
                    c.close()
                except Exception:                                # noqa: BLE001
                    pass
        return sent
