# backend/tests/test_spam_purge.py
# 스팸은 저장하지 않는다(유저 요청): 이미 들어온 스팸은 일괄 삭제, 일반 메일은 그대로.
from sqlmodel import select

from app.models import Email, ExternalLink
from app.worker.sync_jobs import purge_spam
from tests._factories import make_email, make_mail_account


def test_purge_spam_removes_spam_and_links_keeps_normal(session):
    s, _ = session
    make_mail_account(s, id="work", name="회사", tone="coral", sort_order=0)
    make_email(s, id="keep", account="work", subject="보통 메일")
    junk = make_email(s, id="junk", account="work", subject="스팸 메일")
    junk.folder = "spam"
    s.add(junk)
    s.add(ExternalLink(id="xl-junk", account_id="work", external_id="x-junk",
                       entity_type="email", entity_id="junk"))
    s.add(ExternalLink(id="xl-keep", account_id="work", external_id="x-keep",
                       entity_type="email", entity_id="keep"))
    s.commit()

    assert purge_spam(s) == 1  # 스팸 1통만 삭제
    assert s.get(Email, "junk") is None  # 스팸 메일 제거
    assert s.get(Email, "keep") is not None  # 일반 메일 유지
    # 스팸의 ExternalLink 도 제거(일반 것은 유지) — 재유입/유령 링크 방지.
    remaining = sorted(lk.external_id for lk in s.exec(select(ExternalLink)).all())
    assert remaining == ["x-keep"]
