"""updated-projects-report-view

Revision ID: 0247
Revises: 0246
Create Date: 2022-10-20 08:23:18.373501

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


# revision identifiers, used by Alembic.
revision = '0247'
down_revision = '0246'
branch_labels = None
depends_on = None


def upgrade():
    op.execute("""
        CREATE OR REPLACE VIEW projects_report_view AS
        SELECT
            p.id,
            p.created_at,
            p.updated_at,
            p.owner_id,
            p.created_by_id,
            p.is_template,
            p.is_archived,
            p.org_members_can_observe,
            p.org_members_can_autojoin,
            p.default_org_member_permission,
            p.import_status,
            p.total_invites,
            p.default_org_member_role_id,
            p.is_public,
            p.send_emails,
            p.allow_anon_inbound_emails,
            p.include_in_template_library,
            p.copied_from_template_id,
            c.last_activity_at,
            (SELECT COUNT(*) FROM project_members WHERE project_id = p.id) nb_members,
            (SELECT COUNT(*) FROM cards WHERE project_id = p.id) nb_cards,
            (SELECT MAX(last_activity_at) FROM cards WHERE project_id = p.id) last_card_activity_at,
            (SELECT COUNT(*) FROM automation_rules WHERE project_id = p.id) nb_automations,
            (SELECT COUNT(*) FROM views WHERE project_id = p.id) nb_views,
            (SELECT COUNT(*) FROM views WHERE project_id = p.id AND mode='form') nb_forms
        FROM projects p JOIN cards c ON c.id = p.top_level_card_id
    """)


def downgrade():
    pass
