"""Add DimTime dimension and time_id relation to FactUsage.

Revision ID: 9636e66fc187
Revises: bfd15efaf68d
Create Date: 2026-01-19 15:43:51.452260

"""

from typing import Sequence, Union

import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "9636e66fc187"
down_revision: Union[str, None] = "bfd15efaf68d"
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! ###
    op.create_table(
        "dim_time",
        sa.Column("time_id", sa.Integer(), nullable=False),
        sa.Column("time", sa.Time(), nullable=False),
        sa.Column("hour", sa.SmallInteger(), nullable=False),
        sa.Column("minute", sa.SmallInteger(), nullable=False),
        sa.Column("second", sa.SmallInteger(), nullable=False),
        sa.Column("hour_of_day", sa.SmallInteger(), nullable=False),
        sa.Column("is_business_hours", sa.Boolean(), nullable=False),
        sa.Column("time_period", sa.Text(), nullable=False),
        sa.PrimaryKeyConstraint("time_id"),
    )
    op.create_index(op.f("ix_dim_time_hour"), "dim_time", ["hour"], unique=False)
    op.create_index(
        op.f("ix_dim_time_hour_of_day"), "dim_time", ["hour_of_day"], unique=False
    )
    op.create_index(
        op.f("ix_dim_time_is_business_hours"),
        "dim_time",
        ["is_business_hours"],
        unique=False,
    )
    op.create_index(op.f("ix_dim_time_time"), "dim_time", ["time"], unique=True)
    op.create_index(
        op.f("ix_dim_time_time_period"), "dim_time", ["time_period"], unique=False
    )
    op.add_column("fact_usage", sa.Column("time_id", sa.Integer(), nullable=True))
    op.create_index("idx_usage_time", "fact_usage", ["time_id"], unique=False)
    op.create_foreign_key(
        None, "fact_usage", "dim_time", ["time_id"], ["time_id"], ondelete="SET NULL"
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, "fact_usage", type_="foreignkey")
    op.drop_index("idx_usage_time", table_name="fact_usage")
    op.drop_column("fact_usage", "time_id")
    op.drop_index(op.f("ix_dim_time_time_period"), table_name="dim_time")
    op.drop_index(op.f("ix_dim_time_time"), table_name="dim_time")
    op.drop_index(op.f("ix_dim_time_is_business_hours"), table_name="dim_time")
    op.drop_index(op.f("ix_dim_time_hour_of_day"), table_name="dim_time")
    op.drop_index(op.f("ix_dim_time_hour"), table_name="dim_time")
    op.drop_table("dim_time")
    # ### end Alembic commands ###
