"""email_templates

Revision: 0163
Revision ID: d8e7e0bbb09
Revises: 41184106cb68
Create Date: 2019-03-21 14:41:02.259607

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


# revision identifiers, used by Alembic.
revision = 'd8e7e0bbb09'
down_revision = '41184106cb68'
branch_labels = None
depends_on = None


def upgrade():
    op.create_table('email_templates',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('owner_id', sa.Integer(), nullable=False),
        sa.Column('project_id', sa.Integer(), nullable=False),
        sa.Column('created_at', sa.DateTime(), nullable=True),
        sa.Column('updated_at', sa.DateTime(), nullable=True),
        sa.Column('created_by_id', sa.Integer(), nullable=True),
        sa.Column('name', sa.String(), nullable=True),
        sa.Column('subject', sa.String(), nullable=True),
        sa.Column('body', sa.Text(), nullable=True),
        sa.Column('sender', sa.String(), nullable=True),
        sa.Column('attachments_from_attributes', postgresql.ARRAY(sa.String), nullable=True),
        sa.Column('render_error', sa.String(), nullable=True),
        sa.ForeignKeyConstraint(['owner_id'], ['organizations.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['project_id'], ['projects.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_email_templates_project_id'), 'email_templates', ['project_id'], unique=False)

    op.execute("""
        UPDATE role_permissions SET actions = array_append(actions, 'MANAGE_EMAIL_TEMPLATES')
        FROM roles WHERE roles.id = role_permissions.role_id
        AND roles.builtin = 'ADMIN'
        AND role_permissions.object_type = 'project'
        AND role_permissions.object_id IS NULL
        AND NOT (role_permissions.actions @> '{"MANAGE_EMAIL_TEMPLATES"}'::varchar[])
    """)

    op.execute("""
        UPDATE roles SET cache_id = uuid_generate_v4()
        WHERE roles.id IN (
            SELECT DISTINCT roles.id
            FROM roles, role_permissions
            WHERE role_permissions.role_id = roles.id
            AND roles.builtin = 'ADMIN'
            AND role_permissions.object_type = 'project'
            AND role_permissions.object_id IS NULL
            AND (role_permissions.actions @> '{"MANAGE_EMAIL_TEMPLATES"}'::varchar[])
        )
    """)

    op.execute("""
        UPDATE projects SET members_cache_id = uuid_generate_v4()
    """)


def downgrade():
    op.drop_table('email_templates')
