"""mailu — BACKUP overlay: assert both the seeded mailbox (sqlite /data) and the injected
mail message (imap /mail) are present at backup time.

ops.pre_backup created citest@<domain> AND injected a message with subject ccci-backup-probe;
this overlay asserts both are present at the moment the backup snapshot is taken.
The backup→restore divergence is in ops.pre_restore (deletes user + wipes maildir)."""

from __future__ import annotations

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "custom"))
import _mailu  # noqa: E402

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "runner"))
from harness import lifecycle  # noqa: E402

_CI_LOCALPART = "citest"
_CI_MAIL_SUBJECT = "ccci-backup-probe"


def test_backup_captures_mailbox(live_app):
    email = f"{_CI_LOCALPART}@{live_app}"
    cfg = _mailu.config_export(live_app)
    emails = _mailu.user_emails(cfg)
    assert email in emails, (
        f"seeded mailbox {email!r} not found in config-export at backup time; "
        f"users present: {emails}"
    )


def test_backup_captures_mail_message(live_app):
    email = f"{_CI_LOCALPART}@{live_app}"
    out = lifecycle.exec_in_app(
        live_app,
        [
            "sh",
            "-c",
            f"doveadm search -u '{email}' mailbox INBOX header subject '{_CI_MAIL_SUBJECT}'",
        ],
        service="imap",
    )
    assert out.strip(), (
        f"test message {_CI_MAIL_SUBJECT!r} not found in INBOX for {email!r} at backup time; "
        f"the /mail Maildir was not seeded as expected"
    )
