"""add_scan_status_fields

Add background task status fields to architecture_scans table
for harmonized background task architecture.

Revision ID: g5b6c7d8e9f0
Revises: f4a5b6c7d8e9
Create Date: 2024-12-21

"""

from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "g5b6c7d8e9f0"
down_revision: str | None = "f4a5b6c7d8e9"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    # Add status field with default 'completed' for existing records
    # New records will use 'pending' as default
    op.add_column(
        "architecture_scans",
        sa.Column(
            "status",
            sa.String(length=30),
            nullable=False,
            server_default="completed",  # Existing scans are already completed
        ),
    )
    op.create_index(
        op.f("ix_architecture_scans_status"), "architecture_scans", ["status"]
    )

    # Add started_at - for existing records, use timestamp as started_at
    op.add_column(
        "architecture_scans",
        sa.Column("started_at", sa.DateTime(timezone=True), nullable=True),
    )

    # Add completed_at - for existing records, use timestamp + duration as completed_at
    op.add_column(
        "architecture_scans",
        sa.Column("completed_at", sa.DateTime(timezone=True), nullable=True),
    )

    # Add error_message for failed scans
    op.add_column(
        "architecture_scans",
        sa.Column("error_message", sa.Text(), nullable=True),
    )

    # Add progress_message for showing current step
    op.add_column(
        "architecture_scans",
        sa.Column("progress_message", sa.String(length=255), nullable=True),
    )

    # Update existing records to have proper started_at and completed_at
    # This is done via raw SQL for efficiency (PostgreSQL syntax)
    op.execute(
        """
        UPDATE architecture_scans
        SET started_at = timestamp,
            completed_at = timestamp + (COALESCE(duration_seconds, 0) || ' seconds')::interval
        WHERE started_at IS NULL
        """
    )


def downgrade() -> None:
    op.drop_index(op.f("ix_architecture_scans_status"), table_name="architecture_scans")
    op.drop_column("architecture_scans", "progress_message")
    op.drop_column("architecture_scans", "error_message")
    op.drop_column("architecture_scans", "completed_at")
    op.drop_column("architecture_scans", "started_at")
    op.drop_column("architecture_scans", "status")
