"""add users and magic_links tables

Revision ID: 20251021_add_user_and_magic_link
Revises: a1b2c3d4e5f6  # <-- REPLACE with your actual head
Create Date: 2025-10-21
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision: str = '20251021_add_user_and_magic_link'
down_revision: Union[str, None] = '20251021211617'  # <-- REPLACE THIS
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

def upgrade() -> None:
    op.create_table(
        'users',
        sa.Column('id', sa.Integer(), primary_key=True, autoincrement=True),
        sa.Column('email', sa.String(length=255), nullable=False, unique=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column('last_login_at', sa.DateTime(timezone=True), nullable=True),
    )
    op.create_index('ix_users_email', 'users', ['email'], unique=True)

    op.create_table(
        'magic_links',
        sa.Column('id', sa.Integer(), primary_key=True, autoincrement=True),
        sa.Column('token', sa.String(length=128), nullable=False, unique=True),
        sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id', ondelete='CASCADE'), nullable=False),
        sa.Column('purpose', sa.String(length=32), nullable=False),
        sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False),
        sa.Column('used_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column('ip', sa.String(length=64), nullable=True),
        sa.Column('user_agent', sa.String(length=256), nullable=True),
    )
    op.create_index('ix_magic_links_token', 'magic_links', ['token'], unique=True)
    op.create_index('ix_magic_links_user', 'magic_links', ['user_id'])

def downgrade() -> None:
    op.drop_index('ix_magic_links_user', table_name='magic_links')
    op.drop_index('ix_magic_links_token', table_name='magic_links')
    op.drop_table('magic_links')
    op.drop_index('ix_users_email', table_name='users')
    op.drop_table('users')
