"""added shopping list label settings

Revision ID: b04a08da2108
Revises: 5ab195a474eb
Create Date: 2023-21-02 22:03:19.837244

"""
from uuid import uuid4

import sqlalchemy as sa
from sqlalchemy.orm.session import Session

import mealie.db.migration_types
from alembic import op
from mealie.db.models.group.shopping_list import ShoppingList
from mealie.db.models.labels import MultiPurposeLabel

# revision identifiers, used by Alembic.
revision = "b04a08da2108"
down_revision = "5ab195a474eb"
branch_labels = None
depends_on = None


def populate_shopping_lists_multi_purpose_labels(shopping_lists_multi_purpose_labels_table: sa.Table, session: Session):
    shopping_lists = session.query(ShoppingList).all()
    labels = session.query(MultiPurposeLabel).all()

    shopping_lists_labels_data: list[dict] = []
    for shopping_list in shopping_lists:
        for i, label in enumerate(labels):
            shopping_lists_labels_data.append(
                {"id": uuid4(), "shopping_list_id": shopping_list.id, "label_id": label.id, "position": i}
            )

    op.bulk_insert(shopping_lists_multi_purpose_labels_table, shopping_lists_labels_data)
    session.commit()


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    shopping_lists_multi_purpose_labels_table = op.create_table(
        "shopping_lists_multi_purpose_labels",
        sa.Column("created_at", sa.DateTime(), nullable=True),
        sa.Column("update_at", sa.DateTime(), nullable=True),
        sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
        sa.Column("shopping_list_id", mealie.db.migration_types.GUID(), nullable=False),
        sa.Column("label_id", mealie.db.migration_types.GUID(), nullable=False),
        sa.Column("position", sa.Integer(), nullable=False),
        sa.ForeignKeyConstraint(
            ["label_id"],
            ["multi_purpose_labels.id"],
        ),
        sa.ForeignKeyConstraint(
            ["shopping_list_id"],
            ["shopping_lists.id"],
        ),
        sa.PrimaryKeyConstraint("id", "shopping_list_id", "label_id"),
    )
    # ### end Alembic commands ###

    session = Session(bind=op.get_bind())
    populate_shopping_lists_multi_purpose_labels(shopping_lists_multi_purpose_labels_table, session)


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table("shopping_lists_multi_purpose_labels")
    # ### end Alembic commands ###
