"""deduplicate_request_tokens

Revision: 0203
Revision ID: 397b2cb08fff
Revises: 47e876a62c34
Create Date: 2021-02-10 10:25:20.727266

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
import csv
import uuid


# revision identifiers, used by Alembic.
revision = '397b2cb08fff'
down_revision = '47e876a62c34'
branch_labels = None
depends_on = None


requests = sa.Table(
    'requests',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('token', sa.String)
)


def upgrade():
    conn = op.get_bind()
    q = sa.text("""select distinct r1.id, r1.token, coalesce(r1.email, u.email) as email, f.name as form_name, f.project_id
        from requests r1 join request_forms f on f.id = r1.request_form_id left join users u on u.id = r1.user_id, requests r2
        where r1.id > r2.id and r1.token = r2.token order by id""")

    updates = []
    loglines = []
    for r in conn.execute(q):
        token = uuid.uuid4()
        loglines.append([r['id'], r['token'], token, r['email'], r['form_name'], r['project_id']])
        updates.append({'rid': r['id'], 'token': token})

    if loglines:
        with open('requests-duplicates.csv', 'w') as logfile:
            w = csv.writer(logfile)
            w.writerow(["request_id", "old_token", "new_token", "email", "form_name", "project_id"])
            w.writerows(loglines)

    if updates:
        stmt = requests.update().where(requests.c.id==sa.bindparam('rid')).values(token=sa.bindparam('token'))
        conn.execute(stmt, updates)

    op.drop_index(op.f('ix_requests_token'))
    op.create_index(op.f('ix_requests_token'), 'requests', ['token'], unique=True)


def downgrade():
    pass
