"""Adds support for rotation policies.

Creates a default rotation policy (30 days) with the name
'default' ensures that all existing certificates use the default
policy.

Revision ID: a02a678ddc25
Revises: 8ae67285ff14
Create Date: 2017-07-12 11:45:49.257927
"""

# revision identifiers, used by Alembic.
revision = 'a02a678ddc25'
down_revision = '8ae67285ff14'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('rotation_policies',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('name', sa.String(), nullable=True),
        sa.Column('days', sa.Integer(), nullable=True),
        sa.PrimaryKeyConstraint('id')
    )
    op.add_column('certificates', sa.Column('rotation_policy_id', sa.Integer(), nullable=True))
    op.create_foreign_key(None, 'certificates', 'rotation_policies', ['rotation_policy_id'], ['id'])

    conn = op.get_bind()
    stmt = text('insert into rotation_policies (days, name) values (:days, :name)')
    stmt = stmt.bindparams(days=30, name='default')
    conn.execute(stmt)

    stmt = text('select id from rotation_policies where name=:name')
    stmt = stmt.bindparams(name='default')
    rotation_policy_id = conn.execute(stmt).fetchone()[0]

    stmt = text('update certificates set rotation_policy_id=:rotation_policy_id')
    stmt = stmt.bindparams(rotation_policy_id=rotation_policy_id)
    conn.execute(stmt)
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, 'certificates', type_='foreignkey')
    op.drop_column('certificates', 'rotation_policy_id')
    op.drop_index('certificate_replacement_associations_ix', table_name='certificate_replacement_associations')
    op.create_index('certificate_replacement_associations_ix', 'certificate_replacement_associations', ['replaced_certificate_id', 'certificate_id'], unique=True)
    op.drop_table('rotation_policies')
    # ### end Alembic commands ###
