"""add_audit_fields_to_several_models

Revision ID: c412d18de747
Revises: 128b34e77fc7
Create Date: 2025-07-02 19:42:19.251964

"""

from datetime import datetime

import sqlalchemy as sa
from sqlalchemy.sql import column, table

from alembic import op

# revision identifiers, used by Alembic.
revision = "c412d18de747"
down_revision = "128b34e77fc7"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Get current timestamp for existing records
    now = datetime.utcnow()

    # Helper function to add audit columns to a table
    def add_audit_columns(table_name):
        # First add columns as nullable
        op.add_column(table_name, sa.Column("created_at", sa.DateTime(), nullable=True))
        op.add_column(table_name, sa.Column("updated_at", sa.DateTime(), nullable=True))

        # Create a table object for update
        t = table(
            table_name,
            column("created_at", sa.DateTime),
            column("updated_at", sa.DateTime),
        )

        # Update existing records
        op.execute(t.update().values(created_at=now, updated_at=now))

        # Make columns non-nullable
        op.alter_column(
            table_name, "created_at", existing_type=sa.DateTime(), nullable=False
        )
        op.alter_column(
            table_name, "updated_at", existing_type=sa.DateTime(), nullable=False
        )

    # Add audit columns to all tables
    tables = [
        "allergies",
        "conditions",
        "encounters",
        "immunizations",
        "medications",
        "procedures",
        "treatments",
    ]

    for table_name in tables:
        add_audit_columns(table_name)


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("treatments", "updated_at")
    op.drop_column("treatments", "created_at")
    op.drop_column("procedures", "updated_at")
    op.drop_column("procedures", "created_at")
    op.drop_column("medications", "updated_at")
    op.drop_column("medications", "created_at")
    op.drop_column("immunizations", "updated_at")
    op.drop_column("immunizations", "created_at")
    op.drop_column("encounters", "updated_at")
    op.drop_column("encounters", "created_at")
    op.drop_column("conditions", "updated_at")
    op.drop_column("conditions", "created_at")
    op.drop_column("allergies", "updated_at")
    op.drop_column("allergies", "created_at")
    # ### end Alembic commands ###
