# ============================================================
# ADDITIVE: Per-company SMTP credentials - API  (Company Admin + HR)
# Mounted at /api/people/mail/...   (People/mail_urls.py)
# Rights (Employees module): GET = view | add = create | edit / test / default / enable = edit | delete = delete.
# Company Admin always allowed.  EVERYTHING is scoped to the caller's company (B2B).
#
#   GET  settings/                       list   (?audience ?enabled ?q)
#   POST settings/                       add a configuration
#   GET  settings/<id>/                  one configuration (the password is NEVER returned)
#   POST settings/<id>/update/  (PATCH)  edit  (blank / missing password keeps the saved one)
#   POST settings/<id>/delete/  (DELETE) delete
#   POST settings/<id>/test/             connect + log in (+ optional test mail  {"send_to": "..."})
#   POST settings/<id>/set-default/      make it the default for its audience
#   POST settings/<id>/enable/ | disable/
#   GET  settings/meta/                  providers presets, audiences, security modes, limits
#   GET  settings/resolve/               which configuration would be used (?email= ?employee_code= ?candidate_id= ?audience=)
#   GET  logs/   logs/summary/           delivery history (employees + candidates)
#   POST send/                           HR sends an email to employees and / or candidates of THIS company
#   GET/POST welcome/settings/           what the automatic "login ready" mail (candidate converted to employee) contains
#   GET  welcome/<employee_code>/preview/   exactly what would be sent (password masked)
#   POST welcome/<employee_code>/send/      send / resend that mail now
# ============================================================
import re

from django.conf import settings as dj_settings
from django.core.mail import EmailMultiAlternatives
from django.db.models import Count, Q
from django.utils import timezone
from rest_framework import status as http
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet

from Employee.models import EmployeeDT

from . import mail_crypto
from . import mail_engine as me
from .common import PeopleAuthMixin, emp_brief, employees_qs, err, iso, ok, paginate, to_bool
from . import mail_welcome as mw
from .models import CompanyEmailConfig, CompanyEmailLog
from .views_employee_vault import EmployeeBase

DUP_FIELDS = ("name", "mailbox")
MAX_RECIPIENTS = 100


def err_data(code, message, data, status):
    return Response({"status": "error", "code": code, "message": message, "data": data}, status=status)


def cfg_payload(cfg, warnings=None):
    pw = mail_crypto.decrypt(cfg.password_enc) if cfg.password_enc else ""
    d = {
        "id": cfg.id, "name": cfg.name, "audience": cfg.audience, "audience_label": dict(cfg.AUDIENCES)[cfg.audience],
        "host": cfg.host, "port": cfg.port, "security": cfg.security, "username": cfg.username,
        "password_set": bool(cfg.password_enc),
        "password_status": "not_set" if not cfg.password_enc else ("needs_reentry" if pw is None else "saved"),
        "from_email": cfg.from_email, "from_name": cfg.from_name, "reply_to": cfg.reply_to,
        "timeout_seconds": cfg.timeout_seconds, "daily_limit": cfg.daily_limit, "sent_today": me.sent_today(cfg),
        "is_default": cfg.is_default, "enabled": cfg.enabled,
        "last_test": {"at": iso(cfg.last_test_at), "ok": cfg.last_test_ok, "message": cfg.last_test_message},
        "created_by": cfg.created_by, "created_at": iso(cfg.created_at),
        "updated_by": cfg.updated_by, "updated_at": iso(cfg.updated_at),
    }
    if warnings:
        d["warnings"] = warnings
    return d


def field_err(e):
    dup = getattr(e, "field", "") in DUP_FIELDS and ("already" in str(e) or "exists" in str(e))
    if dup:
        return err("DUPLICATE", str(e), http.HTTP_409_CONFLICT, errors={e.field: str(e)})
    return err("VALIDATION", str(e), errors={e.field: str(e)})


# ================================================================ configurations
class MailSettingsViewSet(PeopleAuthMixin, ViewSet):
    lookup_value_regex = r"\d+"
    permission_action_map = {"list": "view", "retrieve": "view", "meta": "view", "resolve": "view", "create": "create",
                             "partial_update": "edit", "destroy": "delete", "test": "edit", "set_default": "edit",
                             "enable": "edit", "disable": "edit"}

    def _get(self, pk):
        return (CompanyEmailConfig.objects.filter(company=self.company(), pk=pk).select_related("company").first())

    # ---- list / detail
    def list(self, request):
        p = request.query_params
        qs = CompanyEmailConfig.objects.filter(company=self.company())
        if (p.get("audience") or "").strip():
            a = p["audience"].strip().upper()
            if a not in me.AUDIENCES:
                return err("VALIDATION", "audience must be ALL, EMPLOYEE or CANDIDATE.")
            qs = qs.filter(audience=a)
        if p.get("enabled") not in (None, ""):
            qs = qs.filter(enabled=to_bool(p["enabled"]))
        q = (p.get("q") or "").strip()
        if q:
            qs = qs.filter(Q(name__icontains=q) | Q(host__icontains=q) | Q(from_email__icontains=q) | Q(username__icontains=q))
        rows, pg = paginate(request, qs.order_by("audience", "-is_default", "id"), cfg_payload)
        return ok("MAIL_SETTINGS", "SMTP configurations.", rows, meta=pg)

    def retrieve(self, request, pk=None):
        c = self._get(pk)
        if c is None:
            return err("NOT_FOUND", "SMTP configuration not found.", http.HTTP_404_NOT_FOUND)
        return ok("MAIL_SETTING", "SMTP configuration.", cfg_payload(c))

    # ---- create
    def create(self, request):
        company, d, actor = self.company(), request.data, self.actor()
        try:
            fields, pw, warnings = me.clean_config(d)
            fields["enabled"] = to_bool(d.get("enabled"), True)
            c = me.save_config(company, CompanyEmailConfig(), fields, pw, actor, make_default=to_bool(d.get("is_default")))
        except me.FieldError as e:
            return field_err(e)
        return ok("MAIL_SETTING_CREATED", f"SMTP configuration '{c.name}' added.", cfg_payload(c, warnings),
                  status=http.HTTP_201_CREATED)

    # ---- update
    def partial_update(self, request, pk=None):
        c, d = self._get(pk), request.data
        if c is None:
            return err("NOT_FOUND", "SMTP configuration not found.", http.HTTP_404_NOT_FOUND)
        try:
            fields, pw, warnings = me.clean_config(d, existing=c)
            if "enabled" in d:
                fields["enabled"] = to_bool(d["enabled"])
            if to_bool(d.get("clear_password")):
                c.password_enc = ""
                if pw is None and (fields.get("username", c.username)):
                    raise me.FieldError("password", "A username needs a password. Send a new password instead of clearing it.")
            if "enabled" in fields and not fields["enabled"]:
                c.is_default = False
            c = me.save_config(self.company(), c, fields, pw, self.actor(), make_default=to_bool(d.get("is_default")))
        except me.FieldError as e:
            return field_err(e)
        return ok("MAIL_SETTING_SAVED", f"SMTP configuration '{c.name}' saved.", cfg_payload(c, warnings))

    # ---- delete
    def destroy(self, request, pk=None):
        c = self._get(pk)
        if c is None:
            return err("NOT_FOUND", "SMTP configuration not found.", http.HTTP_404_NOT_FOUND)
        snap = {"id": c.id, "name": c.name}
        company = c.company
        c.delete()
        me.fix_defaults(company)
        return ok("MAIL_SETTING_DELETED", f"SMTP configuration '{snap['name']}' deleted. Its delivery history is kept.", snap)

    # ---- test connection
    @action(detail=True, methods=["post"], url_path="test")
    def test(self, request, pk=None):
        c = self._get(pk)
        if c is None:
            return err("NOT_FOUND", "SMTP configuration not found.", http.HTTP_404_NOT_FOUND)
        send_to = str(request.data.get("send_to") or "").strip() or None
        try:
            me.check_host(c.host)
            me.check_port(c.port)
            res = me.test_connection(c, send_to, self.actor())
        except me.FieldError as e:
            return field_err(e)
        if res["ok"]:
            return ok("SMTP_TEST_OK", res["message"], res)
        return err_data("SMTP_TEST_FAILED", res["message"], res, http.HTTP_400_BAD_REQUEST)

    # ---- default / enable / disable
    @action(detail=True, methods=["post"], url_path="set-default")
    def set_default(self, request, pk=None):
        c = self._get(pk)
        if c is None:
            return err("NOT_FOUND", "SMTP configuration not found.", http.HTTP_404_NOT_FOUND)
        if not c.enabled:
            return err("VALIDATION", "Enable the configuration before making it the default.")
        if c.is_default:
            return err("DUPLICATE", f"'{c.name}' is already the default for {c.get_audience_display()}.", http.HTTP_409_CONFLICT)
        me.save_config(self.company(), c, {}, None, self.actor(), make_default=True)
        c.refresh_from_db()
        return ok("MAIL_SETTING_DEFAULT", f"'{c.name}' is now the default for {c.get_audience_display()}.", cfg_payload(c))

    def _toggle(self, pk, on):
        c = self._get(pk)
        if c is None:
            return err("NOT_FOUND", "SMTP configuration not found.", http.HTTP_404_NOT_FOUND)
        if c.enabled == on:
            return err("DUPLICATE", f"'{c.name}' is already {'enabled' if on else 'disabled'}.", http.HTTP_409_CONFLICT)
        me.save_config(self.company(), c, {"enabled": on}, None, self.actor())
        c.refresh_from_db()
        return ok("MAIL_SETTING_ENABLED" if on else "MAIL_SETTING_DISABLED",
                  f"'{c.name}' {'enabled' if on else 'disabled'}.", cfg_payload(c))

    @action(detail=True, methods=["post"], url_path="enable")
    def enable(self, request, pk=None):
        return self._toggle(pk, True)

    @action(detail=True, methods=["post"], url_path="disable")
    def disable(self, request, pk=None):
        return self._toggle(pk, False)

    # ---- meta / resolve
    @action(detail=False, methods=["get"], url_path="meta")
    def meta(self, request):
        company = self.company()
        return ok("MAIL_META", "SMTP options.", {
            "audiences": [{"value": v, "label": l} for v, l in CompanyEmailConfig.AUDIENCES],
            "security_modes": [{"value": v, "label": l} for v, l in CompanyEmailConfig.SECURITY],
            "providers": me.PRESETS,
            "limits": {"max_recipients_per_send": MAX_RECIPIENTS, "timeout_seconds": [5, 60], "daily_limit": [0, 1000000],
                       "allowed_ports": list(getattr(dj_settings, "COMPANY_SMTP_ALLOWED_PORTS", me.DEFAULT_PORTS) or []),
                       "test_mails_per_hour": 5},
            "has_configuration": CompanyEmailConfig.objects.filter(company=company, enabled=True).exists(),
            "platform_mailbox_fallback": me.platform_fallback_allowed(),
            "rules": ["Names are unique inside your company.", "One mailbox (host + username) can be added only once.",
                      "One default per audience.", "Passwords are stored encrypted and never shown again.",
                      "Mail to your employees and candidates is sent ONLY through your own SMTP - never through the platform "
                      "(SuperAdmin) mailbox. Without an enabled configuration it is not sent."]})

    @action(detail=False, methods=["get"], url_path="resolve")
    def resolve(self, request):
        company, p = self.company(), request.query_params
        target = None
        if (p.get("email") or "").strip():
            e = EmployeeDT.objects.filter(company=company, email__iexact=p["email"].strip()).first()
        elif (p.get("employee_code") or "").strip():
            e = employees_qs(company).filter(employee_code=p["employee_code"].strip()).first()
        elif (p.get("candidate_id") or "").strip().isdigit():
            e = EmployeeDT.objects.filter(company=company, pk=int(p["candidate_id"])).first()
            if e is not None and employees_qs(company).filter(pk=e.pk).exists():
                e = None                                           # that id is an employee, not a candidate
        elif (p.get("audience") or "").strip().upper() in ("EMPLOYEE", "CANDIDATE"):
            aud = p["audience"].strip().upper()
            cfg = me.choose_config(company, aud)
            return ok("MAIL_RESOLVE", "Configuration for this audience.", {
                "audience": aud, "route": self._route(cfg), "config": self._brief(cfg)})
        else:
            return err("VALIDATION", "Send one of: email, employee_code, candidate_id or audience (EMPLOYEE / CANDIDATE).")
        if e is None:                                  # an outside address mailed BY your company still leaves through your SMTP
            cfg = me.choose_config(company, "EMPLOYEE")
            return ok("MAIL_RESOLVE", "Not an employee or candidate of your company. Mail your company users send to this "
                                      "address leaves through your own SMTP.",
                      {"matched": False, "audience": "OTHER", "route": self._route(cfg), "config": self._brief(cfg)})
        cand = not employees_qs(company).filter(pk=e.pk).exists()
        aud = "CANDIDATE" if cand else "EMPLOYEE"
        cfg = me.choose_config(company, aud)
        return ok("MAIL_RESOLVE", "Configuration that will be used.", {
            "matched": True, "recipient": {**emp_brief(e, request), "type": aud}, "audience": aud,
            "route": self._route(cfg), "config": self._brief(cfg)})

    @staticmethod
    def _route(cfg):
        if cfg is not None:
            return "COMPANY_SMTP"
        return "GLOBAL_FALLBACK" if me.platform_fallback_allowed() else "BLOCKED_NO_SMTP"

    @staticmethod
    def _brief(c):
        return ({"id": c.id, "name": c.name, "audience": c.audience, "from_email": c.from_email, "from_name": c.from_name,
                 "is_default": c.is_default} if c else None)


# ================================================================ logs
def log_row(r):
    return {"id": r.id, "to_email": r.to_email, "recipient_type": r.recipient_type,
            "employee_code": r.employee.employee_code if r.employee_id and r.recipient_type == "EMPLOYEE" else None,
            "candidate_id": r.employee_id if r.recipient_type == "CANDIDATE" else None,
            "subject": r.subject, "kind": r.kind, "status": r.status, "via": r.via, "error": r.error,
            "from_email": r.from_email, "config": r.config_name, "config_id": r.config_id, "sent_by": r.sent_by,
            "created_at": iso(r.created_at)}


class MailLogsView(PeopleAuthMixin, APIView):
    permission_action = "view"

    def get(self, request):
        p, company = request.query_params, self.company()
        qs = CompanyEmailLog.objects.filter(company=company).select_related("employee")
        for key, field, allowed in (("status", "status", ("SENT", "FAILED")), ("audience", "recipient_type", ("EMPLOYEE", "CANDIDATE", "OTHER")),
                                    ("via", "via", ("COMPANY_SMTP", "GLOBAL_FALLBACK"))):
            v = (p.get(key) or "").strip().upper()
            if v:
                if v not in allowed:
                    return err("VALIDATION", f"{key} must be one of {', '.join(allowed)}.")
                qs = qs.filter(**{field: v})
        if (p.get("kind") or "").strip():
            qs = qs.filter(kind=p["kind"].strip())
        if (p.get("config") or "").strip().isdigit():
            qs = qs.filter(config_id=int(p["config"]))
        q = (p.get("q") or "").strip()
        if q:
            qs = qs.filter(Q(to_email__icontains=q) | Q(subject__icontains=q))
        for key, op in (("date_from", "gte"), ("date_to", "lte")):
            if (p.get(key) or "").strip():
                from django.utils.dateparse import parse_date
                d = parse_date(p[key].strip())
                if d is None:
                    return err("VALIDATION", f"{key} must be YYYY-MM-DD.")
                qs = qs.filter(**{f"created_at__date__{op}": d})
        rows, pg = paginate(request, qs, log_row)
        return ok("MAIL_LOGS", "Email delivery history.", rows, meta=pg)


class MailLogsSummaryView(PeopleAuthMixin, APIView):
    permission_action = "view"

    def get(self, request):
        company = self.company()
        qs = CompanyEmailLog.objects.filter(company=company).exclude(kind="smtp_test")
        today = timezone.localdate()
        by_status = {r["status"]: r["n"] for r in qs.values("status").annotate(n=Count("id"))}
        by_aud = {r["recipient_type"]: r["n"] for r in qs.values("recipient_type").annotate(n=Count("id"))}
        by_cfg = [{"config_id": r["config_id"], "config": r["config_name"], "sent": r["n"]}
                  for r in qs.filter(status="SENT").values("config_id", "config_name").annotate(n=Count("id")).order_by("-n")]
        return ok("MAIL_LOG_SUMMARY", "Email delivery summary.", {
            "total": qs.count(), "sent": by_status.get("SENT", 0), "failed": by_status.get("FAILED", 0),
            "sent_today": qs.filter(status="SENT", created_at__date=today).count(),
            "by_recipient_type": by_aud, "by_configuration": by_cfg,
            "global_fallback": qs.filter(via="GLOBAL_FALLBACK").count()})


# ================================================================ compose + send (HR -> employees / candidates)
class MailSendView(PeopleAuthMixin, APIView):
    permission_action = "create"

    def post(self, request):
        company, d, actor = self.company(), request.data, self.actor()
        subject, message = str(d.get("subject") or "").strip(), str(d.get("message") or "").strip()
        html = str(d.get("html") or "").strip()
        kind = re.sub(r"[^a-z0-9_]+", "_", str(d.get("kind") or "announcement").lower())[:40] or "announcement"
        if not subject or len(subject) > 150 or "\n" in subject or "\r" in subject:
            return err("VALIDATION", "subject is required (max 150 characters, one line).")
        if not message or len(message) > 10000:
            return err("VALIDATION", "message is required (max 10000 characters).")
        if len(html) > 50000:
            return err("VALIDATION", "html is too long (max 50000 characters).")
        codes, ids = d.get("employee_codes") or [], d.get("candidate_ids") or []
        if not isinstance(codes, list) or not isinstance(ids, list):
            return err("VALIDATION", "employee_codes and candidate_ids must be lists.")
        codes = list(dict.fromkeys(str(c).strip() for c in codes if str(c).strip()))
        try:
            ids = list(dict.fromkeys(int(i) for i in ids))
        except (TypeError, ValueError):
            return err("VALIDATION", "candidate_ids must be whole numbers.")
        if not codes and not ids:
            return err("VALIDATION", "Send at least one employee_codes or candidate_ids entry.")
        if len(codes) + len(ids) > MAX_RECIPIENTS:
            return err("VALIDATION", f"At most {MAX_RECIPIENTS} recipients per send.")
        emps = {e.employee_code: e for e in employees_qs(company).filter(employee_code__in=codes)}
        cands = {c.id: c for c in EmployeeDT.objects.filter(company=company, id__in=ids)
                 .exclude(id__in=employees_qs(company).values("id"))}
        bad_c, bad_i = [c for c in codes if c not in emps], [i for i in ids if i not in cands]
        if bad_c or bad_i:                              # other companies' people look exactly like unknown ones
            return err("VALIDATION", "Some recipients were not found in your company.",
                       errors={"employee_codes": bad_c, "candidate_ids": bad_i})
        forced = None
        if str(d.get("config_id") or "").strip():
            try:
                forced = CompanyEmailConfig.objects.filter(company=company, pk=int(d["config_id"]), enabled=True).first()
            except (TypeError, ValueError):
                forced = None
            if forced is None:
                return err("VALIDATION", "config_id is not an enabled configuration of your company.")
        people = [("EMPLOYEE", e) for e in emps.values()] + [("CANDIDATE", c) for c in cands.values()]
        skipped, rows = [], []
        for aud, e in people:
            if not (e.email or "").strip():
                skipped.append({"type": aud, "employee_code": e.employee_code, "id": e.id, "reason": "No email address on file."})
                continue
            cfg = forced if forced is not None and forced.audience in ("ALL", aud) else (None if forced is not None else me.choose_config(company, aud))
            if cfg is None:
                return err("NO_SMTP_CONFIG", f"No enabled SMTP configuration for {aud.lower()}s. Add one under Email settings"
                           + (" (the chosen config_id does not cover this audience)." if forced is not None else "."))
            rows.append((aud, e, cfg))
        if not rows:
            return err("VALIDATION", "None of the recipients has an email address.", errors={"skipped": skipped})
        results, conns, batch = [], {}, me.new_batch()
        try:
            for aud, e, cfg in rows:
                body = message.replace("{name}", e.name or "").replace("{company}", getattr(company, "Registered_Company_Name", "") or "")
                msg = EmailMultiAlternatives(subject, body, cfg.from_email, [e.email.strip()],
                                             headers={"X-HRN-Kind": kind, "X-HRN-By": actor})
                if html:
                    msg.attach_alternative(html.replace("{name}", e.name or ""), "text/html")
                route = me.Route(company, cfg, [e.email.strip().lower()], me.classify([e.email.strip().lower()]))
                try:
                    good = me.deliver_via_company(route, msg, True, conns, batch, fail_silently=False)
                    err_text = "" if good else "The server accepted no recipients."
                except me.MailLimitError as ex:
                    good, err_text = False, str(ex)
                except Exception as ex:                          # noqa: BLE001
                    good, err_text = False, me.friendly_error(ex, cfg)
                results.append({"to": e.email, "type": aud, "employee_code": e.employee_code if aud == "EMPLOYEE" else None,
                                "candidate_id": e.id if aud == "CANDIDATE" else None, "status": "SENT" if good else "FAILED",
                                "config": cfg.name, "error": err_text})
        finally:
            for c in conns.values():
                try:
                    c.close()
                except Exception:                                # noqa: BLE001
                    pass
        sent = sum(1 for r in results if r["status"] == "SENT")
        data = {"requested": len(people), "sent": sent, "failed": len(results) - sent, "skipped": skipped, "results": results,
                "configurations_used": sorted({r["config"] for r in results}), "batch_id": batch}
        if sent == 0:
            return err_data("SEND_FAILED", "No email could be sent. See results for the reason.", data, http.HTTP_502_BAD_GATEWAY)
        return ok("MAIL_SENT", f"{sent} email(s) sent." + (f" {len(results) - sent} failed." if len(results) > sent else ""), data)


# ================================================================ employee self view
class MyEmailsView(EmployeeBase, APIView):
    """GET /employee/my-emails/ - mails the company sent to ME (no bodies, no failures)."""

    def get(self, request):
        emp = self.me
        qs = (CompanyEmailLog.objects.filter(company=emp.company, status="SENT")
              .filter(Q(employee=emp) | Q(to_email__iexact=emp.email)).exclude(kind="smtp_test"))
        rows, pg = paginate(request, qs, lambda r: {"id": r.id, "subject": r.subject, "kind": r.kind,
                                                    "from_email": r.from_email, "sent_at": iso(r.created_at)})
        return ok("MY_EMAILS", "Emails my company sent to me.", rows, meta=pg)


# ================================================================ welcome mail (candidate converted -> employee)
def welcome_payload(ws):
    return {"enabled": ws.enabled, "include_password": ws.include_password, "include_salary": ws.include_salary,
            "fields": mw.fields_of(ws), "available_fields": [{"key": k, "label": l} for k, l in mw.FIELD_LABELS.items()],
            "subject": ws.subject, "intro": ws.intro, "footer": ws.footer, "login_url": ws.login_url,
            "placeholders": mw.PLACEHOLDERS, "updated_by": ws.updated_by, "updated_at": iso(ws.updated_at)}


class WelcomeSettingsView(PeopleAuthMixin, APIView):
    """GET / POST  /api/people/mail/welcome/settings/ - what the automatic credentials mail contains."""
    permission_action = "view"

    def get(self, request):
        return ok("WELCOME_SETTINGS", "Welcome email settings.", welcome_payload(mw.get_settings(self.company())))

    def post(self, request):
        from .common import people_allows
        if not people_allows(request.user, "edit"):
            return err("FORBIDDEN", "Changing the welcome email needs the Employees 'edit' right.", http.HTTP_403_FORBIDDEN)
        d, ws = request.data, mw.get_settings(self.company())
        try:
            for f in ("enabled", "include_password", "include_salary"):
                if f in d:
                    setattr(ws, f, to_bool(d[f]))
            if "subject" in d:
                v = str(d["subject"] or "").strip()
                if not v or len(v) > 150 or "\n" in v or "\r" in v:
                    raise ValueError("subject is required: one line, max 150 characters.")
                ws.subject = v
            for f, mx in (("intro", 2000), ("footer", 1000)):
                if f in d:
                    v = str(d[f] or "").strip()
                    if len(v) > mx:
                        raise ValueError(f"{f} is too long (max {mx} characters).")
                    setattr(ws, f, v)
            if "login_url" in d:
                v = str(d["login_url"] or "").strip()
                if v and (not re.match(r"^https?://[^\s]+$", v) or len(v) > 255):
                    raise ValueError("login_url must start with http:// or https:// (max 255 characters).")
                ws.login_url = v
            if "fields" in d:
                v = d["fields"]
                if not isinstance(v, list) or not v:
                    raise ValueError("fields must be a non-empty list. Allowed: " + ", ".join(mw.FIELD_LABELS))
                bad = [x for x in v if x not in mw.FIELD_LABELS]
                if bad:
                    raise ValueError("Unknown field(s): " + ", ".join(map(str, bad)) + ". Allowed: " + ", ".join(mw.FIELD_LABELS))
                ws.fields = list(dict.fromkeys(v))                    # duplicates dropped, order kept
        except ValueError as e:
            return err("VALIDATION", str(e))
        ws.updated_by = self.actor()
        ws.save()
        return ok("WELCOME_SETTINGS_SAVED", "Welcome email settings saved.", welcome_payload(ws))


class WelcomePreviewView(PeopleAuthMixin, APIView):
    """GET /api/people/mail/welcome/<employee_code>/preview/ - exactly what would be sent (password masked)."""
    permission_action = "edit"

    def get(self, request, code):
        company = self.company()
        e = employees_qs(company).filter(employee_code=code).first()
        if e is None:
            return err("NOT_FOUND", "Employee not found.", http.HTTP_404_NOT_FOUND)
        subject, text, html, rows = mw.build(company, e, None, mw.get_settings(company), mask_password=True)
        cfg = me.choose_config(company, "EMPLOYEE")
        return ok("WELCOME_PREVIEW", "Welcome email preview.", {
            "to": e.email, "subject": subject, "text": text, "html": html,
            "details": [{"key": k, "label": l, "value": v} for k, l, v in rows],
            "will_be_sent_from": ({"config": cfg.name, "from_email": cfg.from_email, "from_name": cfg.from_name} if cfg else None),
            "can_send": cfg is not None and bool((e.email or "").strip())})


class WelcomeResendView(PeopleAuthMixin, APIView):
    """POST /api/people/mail/welcome/<employee_code>/send/ - send (or resend) the credentials mail now."""
    permission_action = "edit"

    def post(self, request, code):
        company = self.company()
        e = employees_qs(company).filter(employee_code=code).first()
        if e is None:
            return err("NOT_FOUND", "Employee not found.", http.HTTP_404_NOT_FOUND)
        res = mw.send_welcome(company, e, actor=self.actor(), auto=False)
        if res["sent"]:
            return ok("WELCOME_SENT", f"Welcome email sent to {res['to']}.", res)
        code_ = "NO_SMTP_CONFIG" if res["status"] == "NO_SMTP_CONFIG" else "SEND_FAILED"
        return err_data(code_, res["message"], res, http.HTTP_400_BAD_REQUEST if res["status"] in ("NO_SMTP_CONFIG", "NO_EMAIL") else http.HTTP_502_BAD_GATEWAY)
