"""Worklog model — immutable internal time-tracking records."""

import uuid
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey, Text, Index, func
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.orm import relationship

from app.database import Base


class Worklog(Base):
    """Internal worklog entry with integrity hash for audit compliance.

    Each worklog is tied to an Aegis entity (test, campaign, etc.) and
    optionally synced to Tempo.  The ``integrity_hash`` is a SHA-256 of
    the immutable fields so tampering can be detected.
    """

    __tablename__ = "worklogs"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    entity_type = Column(String(50), nullable=False)
    entity_id = Column(UUID(as_uuid=True), nullable=False)
    user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
    activity_type = Column(String(100), nullable=False)
    started_at = Column(DateTime, nullable=False)
    ended_at = Column(DateTime)
    duration_seconds = Column(Integer, nullable=False)
    description = Column(Text)
    tempo_synced = Column(DateTime)
    tempo_worklog_id = Column(String(100))
    integrity_hash = Column(String(64))
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    extra_metadata = Column("metadata", JSONB, default={})

    user = relationship("User", foreign_keys=[user_id])

    __table_args__ = (
        Index("ix_worklogs_entity_id", "entity_id"),
        Index("ix_worklogs_user_id", "user_id"),
        Index("ix_worklogs_entity_type_entity_id", "entity_type", "entity_id"),
    )
