"""Add source field to RawMeasurement.

Revision ID: e0d5bb6c3974
Revises: 1646629c1c90
Create Date: 2026-01-06 21:30:21.741949

"""

from typing import Sequence, Union

import sqlalchemy as sa

from alembic import op
from iot_db.models.base import Sources

# revision identifiers, used by Alembic.
revision: str = "e0d5bb6c3974"
down_revision: Union[str, None] = "1646629c1c90"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # Add column as nullable first
    op.add_column(
        "measurement_raw", sa.Column("source", sa.SmallInteger(), nullable=True)
    )
    # Set default value (sensorhub) for existing rows
    op.execute(
        f"UPDATE measurement_raw SET source = {Sources.sensorhub.value} WHERE source IS NULL"
    )
    # Make column NOT NULL with server default
    op.alter_column(
        "measurement_raw",
        "source",
        nullable=False,
        server_default=str(Sources.sensorhub.value),
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # Remove server default before dropping column
    op.alter_column("measurement_raw", "source", server_default=None)
    op.drop_column("measurement_raw", "source")
    # ### end Alembic commands ###
