"""added household recipe lock setting and household management user permission

Revision ID: be568e39ffdf
Revises: feecc8ffb956
Create Date: 2024-09-02 21:39:49.210355

"""

from textwrap import dedent

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = "be568e39ffdf"
down_revision = "feecc8ffb956"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None


def populate_defaults():
    if op.get_context().dialect.name == "postgresql":
        TRUE = "TRUE"
        FALSE = "FALSE"
    else:
        TRUE = "1"
        FALSE = "0"

    op.execute(
        dedent(
            f"""
            UPDATE household_preferences
            SET lock_recipe_edits_from_other_households = {TRUE}
            WHERE lock_recipe_edits_from_other_households IS NULL
            """
        )
    )
    op.execute(
        dedent(
            f"""
            UPDATE users
            SET can_manage_household = {FALSE}
            WHERE can_manage_household IS NULL AND admin = {FALSE}
            """
        )
    )
    op.execute(
        dedent(
            f"""
            UPDATE users
            SET can_manage_household = {TRUE}
            WHERE can_manage_household IS NULL AND admin = {TRUE}
            """
        )
    )


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "household_preferences",
        sa.Column("lock_recipe_edits_from_other_households", sa.Boolean(), nullable=True),
    )
    op.add_column("users", sa.Column("can_manage_household", sa.Boolean(), nullable=True))
    # ### end Alembic commands ###

    populate_defaults()


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("users", "can_manage_household")
    op.drop_column("household_preferences", "lock_recipe_edits_from_other_households")
    # ### end Alembic commands ###
