"""empty message

Revision ID: 346845842745
Revises: 5127776ebf69
Create Date: 2023-05-22 15:09:50.064617

"""
from alembic import op
import sqlalchemy as sa

from app.models import Entry


# revision identifiers, used by Alembic.
revision = "346845842745"
down_revision = "5127776ebf69"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("entry", schema=None) as batch_op:
        batch_op.add_column(
            sa.Column(
                "weight_difference", sa.Integer(), nullable=False, server_default="0"
            )
        )

    # Commit the table alteration commands
    op.execute("COMMIT")

    # ### end Alembic commands ###
    # Retrieve all existing Entry records
    session = sa.orm.Session(bind=op.get_bind())
    entries = session.query(Entry).all()

    print(f"Found {len(entries)}")

    # Update the weight_difference column for each entry
    for entry in entries:
        print(f"processing {entry.id}")
        # Perform the necessary calculation to update the weight_difference
        previous_entry = (
            Entry.query.filter(
                Entry.date < entry.date,
                Entry.user_id == entry.user_id,
                Entry.active_record.is_(True),
            )
            .order_by(Entry.date.desc())
            .first()
        )

        if previous_entry:
            if entry.weight > previous_entry.weight:
                entry.weight_difference = 1  # Gain
            elif entry.weight < previous_entry.weight:
                entry.weight_difference = -1  # Loss
            else:
                entry.weight_difference = 0  # No change
        else:
            entry.weight_difference = 0  # No change for the first entry

        # Update the weight_difference column in the entry table
        print("executing db statement")
        op.execute(
            sa.text(
                "UPDATE entry SET weight_difference = :weight_diff WHERE id = :entry_id"
            ).bindparams(weight_diff=entry.weight_difference, entry_id=entry.id)
        )


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("entry", schema=None) as batch_op:
        batch_op.drop_column("weight_difference")

    # ### end Alembic commands ###
