"""Phase 2.1c: nature métier et segments d'exécution."""
from alembic import op
import sqlalchemy as sa

revision = "j5e6f7a8b9c0"
down_revision = "i4d5e6f7a8b9"
branch_labels = None
depends_on = None


def upgrade():
    columns = [
        sa.Column("task_nature", sa.String(30), nullable=False, server_default="unknown"),
        sa.Column("interruptible", sa.Boolean(), nullable=False, server_default=sa.false()),
        sa.Column("splittable", sa.Boolean(), nullable=False, server_default=sa.false()),
        sa.Column("minimum_segment_minutes", sa.Integer(), nullable=True),
        sa.Column("allow_next_day_resume", sa.Boolean(), nullable=False, server_default=sa.false()),
        sa.Column("requires_safe_pause", sa.Boolean(), nullable=False, server_default=sa.false()),
    ]
    for column in columns:
        op.add_column("lot_tasks", column)
    op.create_table(
        "task_execution_segments",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("scheduled_task_id", sa.Integer(), nullable=False),
        sa.Column("technician_id", sa.Integer(), nullable=True),
        sa.Column("started_at", sa.DateTime(), nullable=False),
        sa.Column("ended_at", sa.DateTime(), nullable=True),
        sa.Column("duration_minutes", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("status", sa.String(20), nullable=False, server_default="active"),
        sa.Column("pause_reason", sa.String(80), nullable=True),
        sa.Column("note", sa.Text(), nullable=True),
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.ForeignKeyConstraint(["scheduled_task_id"], ["scheduled_tasks.id"], ondelete="CASCADE"),
        sa.ForeignKeyConstraint(["technician_id"], ["users.id"], ondelete="SET NULL"),
    )
    op.create_index("ix_task_execution_segments_scheduled_task_id", "task_execution_segments", ["scheduled_task_id"])
    op.create_index("ix_task_execution_segments_technician_id", "task_execution_segments", ["technician_id"])


def downgrade():
    op.drop_index("ix_task_execution_segments_technician_id", table_name="task_execution_segments")
    op.drop_index("ix_task_execution_segments_scheduled_task_id", table_name="task_execution_segments")
    op.drop_table("task_execution_segments")
    for name in ("requires_safe_pause", "allow_next_day_resume", "minimum_segment_minutes", "splittable", "interruptible", "task_nature"):
        op.drop_column("lot_tasks", name)
