from datetime import UTC, datetime, timedelta

from gnexus_creds.schemas import SecretCreate, SecretFieldIn, SecretUpdate
from gnexus_creds.services import (
    create_secret,
    is_expired,
    list_versions,
    reveal_secret,
    update_secret,
)


def test_secret_versioning_and_reveal(db_session, actor):
    created = create_secret(
        db_session,
        actor,
        SecretCreate(
            title="Facebook",
            purpose="facebook.com",
            category="social",
            tags=["Social", "Login"],
            fields=[
                SecretFieldIn(name="login", value="me@example.test", encrypted=False, position=1),
                SecretFieldIn(
                    name="password", value="secret", encrypted=True, masked=True, position=2
                ),
            ],
        ),
    )
    db_session.commit()

    versions = list_versions(db_session, actor, created.id)
    assert len(versions) == 1

    update_secret(db_session, actor, created.id, SecretUpdate(notes="short note"))
    db_session.commit()
    assert len(list_versions(db_session, actor, created.id)) == 1

    update_secret(
        db_session,
        actor,
        created.id,
        SecretUpdate(
            fields=[SecretFieldIn(name="password", value="new-secret", encrypted=True, position=1)]
        ),
    )
    db_session.commit()
    assert len(list_versions(db_session, actor, created.id)) == 2

    revealed = reveal_secret(db_session, actor, created.id)
    values = {field.name: field.value for field in revealed.fields}
    assert values["password"] == "new-secret"


def test_is_expired_handles_sqlite_naive_datetime():
    now = datetime.now(UTC)
    naive_start = (now - timedelta(minutes=2)).replace(tzinfo=None)
    assert is_expired(naive_start, now=now, delta=timedelta(minutes=1))
