from datetime import datetime, timezone, timedelta
from uuid import uuid4
from app_new.extensions import db
from app_new.core.models.settings import AppSettings
from app_new.core.models.maintenance import WatchdogLog
from app_new.logs.routes import apply_retention


def test_encrypted_application_setting_is_not_stored_in_plain_text(app):
    with app.app_context():
        key = f"secret-{uuid4().hex}"
        AppSettings.set("test_encrypted_secret", key, is_encrypted=True)
        row = AppSettings.query.filter_by(key="test_encrypted_secret").one()
        assert row.value.startswith("enc:") and key not in row.value
        assert AppSettings.get("test_encrypted_secret") == key


def test_watchdog_log_retention_removes_only_expired_rows(app):
    with app.app_context():
        old = WatchdogLog(watchdog_name="test", level="info", message="old", created_at=datetime.now(timezone.utc)-timedelta(days=100))
        recent = WatchdogLog(watchdog_name="test", level="info", message="recent", created_at=datetime.now(timezone.utc))
        db.session.add_all([old, recent]); db.session.commit(); old_id, recent_id = old.id, recent.id
        with app.test_request_context(method="POST", data={"days":"30"}):
            assert apply_retention.__wrapped__().status_code == 302
        assert db.session.get(WatchdogLog, old_id) is None
        assert db.session.get(WatchdogLog, recent_id) is not None
