"""mailu — RESTORE overlay: assert both the seeded mailbox (sqlite /data) and the injected
mail message (imap /mail) are back after restore.

ops.pre_restore deleted the user from sqlite AND wiped the maildir to simulate full data
loss on both volumes; this overlay asserts that abra app restore brings back both the
account record (from /data) and the stored message (from /mail)."""

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_restore_returns_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 after restore; "
        f"the /data (sqlite) volume was not restored. "
        f"users present: {emails}"
    )


def test_restore_returns_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} after restore; "
        f"the /mail (Maildir) volume was not restored from the backup snapshot"
    )
