"""Worklog service tests — integrity hash (FASE-1.5)."""

from datetime import datetime
from uuid import uuid4

from app.services import worklog_service


def test_create_worklog_sets_integrity_hash(db, admin_user):
    entity_id = uuid4()
    started = datetime(2026, 5, 18, 9, 0, 0)
    wl = worklog_service.create_worklog(
        db,
        entity_type="test",
        entity_id=entity_id,
        user_id=admin_user.id,
        activity_type="red_team",
        started_at=started,
        duration_seconds=3600,
        description="Manual entry",
    )
    db.commit()
    db.refresh(wl)

    assert wl.integrity_hash
    assert len(wl.integrity_hash) == 64
    assert worklog_service.verify_worklog_integrity(wl) is True


def test_verify_worklog_integrity_detects_tampering(db, admin_user):
    wl = worklog_service.create_worklog(
        db,
        entity_type="test",
        entity_id=uuid4(),
        user_id=admin_user.id,
        activity_type="blue_validation",
        started_at=datetime(2026, 5, 18, 10, 0, 0),
        duration_seconds=1800,
    )
    db.commit()
    db.refresh(wl)

    wl.duration_seconds = 9999
    assert worklog_service.verify_worklog_integrity(wl) is False


def test_list_worklogs_filters_by_entity(db, admin_user):
    eid = uuid4()
    worklog_service.create_worklog(
        db,
        entity_type="campaign",
        entity_id=eid,
        user_id=admin_user.id,
        activity_type="reporting",
        started_at=datetime(2026, 5, 18, 11, 0, 0),
        duration_seconds=600,
    )
    db.commit()

    rows = worklog_service.list_worklogs(
        db, entity_type="campaign", entity_id=eid,
    )
    assert len(rows) == 1
    assert rows[0].entity_id == eid
