"""
SQLAlchemy model for validation job queue.

The validation_jobs table is the durable queue: API inserts pending rows,
workers atomically claim and process them.
"""

from __future__ import annotations

import uuid
from datetime import datetime, timezone

from sqlalchemy import JSON, Column, DateTime, Index, Integer, String, Text

from pycharter.db.models.base import Base


def _utc_now() -> datetime:
    return datetime.now(timezone.utc)


def _default_id() -> str:
    return str(uuid.uuid4())


class ValidationJobModel(Base):
    """
    One row per validation job.

    Lifecycle: pending -> claimed -> completed | failed | dead_letter | cancelled
    """

    __tablename__ = "validation_jobs"

    id = Column(String(36), primary_key=True, default=_default_id)

    # Domain columns
    contract_name = Column(String(255), nullable=False)
    contract_version = Column(String(50), nullable=False, default="latest")
    data_json = Column(JSON, nullable=False)  # {data_source, options}

    # Queue columns
    status = Column(String(20), nullable=False, default="pending")
    fires_at = Column(DateTime(timezone=True), nullable=False, default=_utc_now)
    claimed_by = Column(String(255), nullable=True)
    claimed_at = Column(DateTime(timezone=True), nullable=True)

    attempt = Column(Integer, nullable=False, default=0)
    max_attempts = Column(Integer, nullable=False, default=5)
    error_message = Column(Text, nullable=True)

    idempotency_key = Column(String(255), nullable=True, unique=True)

    # Result columns
    created_at = Column(DateTime(timezone=True), default=_utc_now)
    completed_at = Column(DateTime(timezone=True), nullable=True)
    result_json = Column(JSON, nullable=True)

    __table_args__ = (
        Index("ix_validation_jobs_poll", "status", "fires_at"),
        {"schema": "pycharter"},
    )
