"""single identifier signup, marketing consent, customer profile

Revision ID: b79b129b318a
Revises: ed1ee23ab5ed
Create Date: 2026-07-20 16:41:54.213630

"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = "b79b129b318a"
down_revision: Union[str, None] = "ed1ee23ab5ed"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # NOTE: autogenerate also proposed op.drop_table('spatial_ref_sys')
    # (a PostGIS system table — dropping it would break PostGIS
    # entirely) and dropping refresh_tokens_token_hash_key (recurring,
    # pre-existing unique-index-vs-named-constraint drift unrelated to
    # this migration — same drift called out in 42828b3f2eea). Both
    # removed by hand.
    op.create_table(
        "customer_profiles",
        sa.Column("id", sa.Uuid(), nullable=False),
        sa.Column("user_id", sa.Uuid(), nullable=False),
        sa.Column("gender", sa.String(length=30), nullable=True),
        sa.Column("nationality", sa.String(length=100), nullable=True),
        sa.Column("date_of_birth", sa.Date(), nullable=True),
        sa.Column("default_language", sa.String(length=10), nullable=True),
        sa.Column("address", sa.String(length=255), nullable=True),
        sa.Column("default_delivery_address", sa.String(length=255), nullable=True),
        sa.Column("default_delivery_latitude", sa.Float(), nullable=True),
        sa.Column("default_delivery_longitude", sa.Float(), nullable=True),
        sa.Column(
            "created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False
        ),
        sa.Column(
            "updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False
        ),
        sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("user_id"),
    )

    # otp_verifications rows are short-lived (minutes) and keyed by a
    # request/response contract that's changing in this same release
    # (phone -> identifier, which isn't always a phone anymore) — any
    # in-flight OTP can't be completed across this deploy regardless,
    # so it's simplest and safest to clear the table rather than try
    # to backfill a column whose meaning changed.
    op.execute("DELETE FROM otp_verifications")
    op.add_column(
        "otp_verifications",
        sa.Column("identifier", sa.String(length=255), nullable=False),
    )
    op.drop_index("ix_otp_verifications_phone", table_name="otp_verifications")
    op.create_index(
        op.f("ix_otp_verifications_identifier"),
        "otp_verifications",
        ["identifier"],
        unique=False,
    )
    op.drop_column("otp_verifications", "pending_email")
    op.drop_column("otp_verifications", "phone")

    op.add_column(
        "users",
        sa.Column(
            "marketing_emails_opt_in",
            sa.Boolean(),
            nullable=False,
            server_default=sa.false(),
        ),
    )
    op.alter_column("users", "marketing_emails_opt_in", server_default=None)
    op.alter_column(
        "users", "email", existing_type=sa.VARCHAR(length=255), nullable=True
    )


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column(
        "users", "email", existing_type=sa.VARCHAR(length=255), nullable=False
    )
    op.drop_column("users", "marketing_emails_opt_in")
    # Same reasoning as upgrade()'s DELETE: these rows are short-lived
    # and the column being re-added (phone, NOT NULL) can't be
    # backfilled from identifier (which isn't always a phone).
    op.execute("DELETE FROM otp_verifications")
    op.add_column(
        "otp_verifications",
        sa.Column("phone", sa.VARCHAR(length=20), autoincrement=False, nullable=False),
    )
    op.add_column(
        "otp_verifications",
        sa.Column(
            "pending_email", sa.VARCHAR(length=255), autoincrement=False, nullable=True
        ),
    )
    op.drop_index(
        op.f("ix_otp_verifications_identifier"), table_name="otp_verifications"
    )
    op.create_index(
        "ix_otp_verifications_phone", "otp_verifications", ["phone"], unique=False
    )
    op.drop_column("otp_verifications", "identifier")
    op.create_table(
        "spatial_ref_sys",
        sa.Column("srid", sa.INTEGER(), autoincrement=False, nullable=False),
        sa.Column(
            "auth_name", sa.VARCHAR(length=256), autoincrement=False, nullable=True
        ),
        sa.Column("auth_srid", sa.INTEGER(), autoincrement=False, nullable=True),
        sa.Column(
            "srtext", sa.VARCHAR(length=2048), autoincrement=False, nullable=True
        ),
        sa.Column(
            "proj4text", sa.VARCHAR(length=2048), autoincrement=False, nullable=True
        ),
        sa.CheckConstraint(
            "srid > 0 AND srid <= 998999", name="spatial_ref_sys_srid_check"
        ),
        sa.PrimaryKeyConstraint("srid", name="spatial_ref_sys_pkey"),
    )
    op.drop_table("customer_profiles")
    # ### end Alembic commands ###
