"""
Deletion Job Model
Tracks tenant deletion jobs for persistence and recovery
"""

from sqlalchemy import Column, String, DateTime, Text, JSON, Index, Integer
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
import uuid

from shared.database.base import Base


class DeletionJob(Base):
    """
    Persistent storage for tenant deletion jobs
    Enables job recovery and tracking across service restarts
    """
    __tablename__ = "deletion_jobs"

    # Primary identifiers
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, index=True)
    job_id = Column(String(100), nullable=False, unique=True, index=True)  # External job ID
    tenant_id = Column(UUID(as_uuid=True), nullable=False, index=True)

    # Job Metadata
    tenant_name = Column(String(255), nullable=True)
    initiated_by = Column(UUID(as_uuid=True), nullable=True)  # User ID who started deletion

    # Job Status
    status = Column(String(50), nullable=False, default="pending", index=True)  # pending, in_progress, completed, failed, rolled_back

    # Service Results
    service_results = Column(JSON, nullable=True)  # Dict of service_name -> result details

    # Progress Tracking
    total_items_deleted = Column(Integer, default=0, nullable=False)
    services_completed = Column(Integer, default=0, nullable=False)
    services_failed = Column(Integer, default=0, nullable=False)

    # Error Tracking
    error_log = Column(JSON, nullable=True)  # Array of error messages

    # Timestamps
    started_at = Column(DateTime(timezone=True), nullable=True, index=True)
    completed_at = Column(DateTime(timezone=True), nullable=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)

    # Additional Context
    notes = Column(Text, nullable=True)
    extra_metadata = Column(JSON, nullable=True)  # Additional job-specific data

    # Indexes for performance
    __table_args__ = (
        Index('idx_deletion_job_id', 'job_id'),
        Index('idx_deletion_tenant_id', 'tenant_id'),
        Index('idx_deletion_status', 'status'),
        Index('idx_deletion_started_at', 'started_at'),
        Index('idx_deletion_tenant_status', 'tenant_id', 'status'),
    )

    def __repr__(self):
        return f"<DeletionJob(job_id='{self.job_id}', tenant_id={self.tenant_id}, status='{self.status}')>"
