"""Create ExternalOrganization

Revision ID: 7b35e72d3a15
Revises: 3020ecbe171e
Create Date: 2024-07-15 13:35:18.495080

"""

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

from polar.enums import Platforms

# Polar Custom Imports
from polar.kit.extensions.sqlalchemy import StringEnum

# revision identifiers, used by Alembic.
revision = "7b35e72d3a15"
down_revision = "3020ecbe171e"
branch_labels: tuple[str] | None = None
depends_on: tuple[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "external_organizations",
        sa.Column("platform", StringEnum(Platforms), nullable=False),
        sa.Column("name", postgresql.CITEXT(), nullable=False),
        sa.Column("external_id", sa.BigInteger(), nullable=False),
        sa.Column("avatar_url", sa.String(), nullable=False),
        sa.Column("is_personal", sa.Boolean(), nullable=False),
        sa.Column("installation_id", sa.Integer(), nullable=True),
        sa.Column(
            "installation_created_at", sa.TIMESTAMP(timezone=True), nullable=True
        ),
        sa.Column(
            "installation_updated_at", sa.TIMESTAMP(timezone=True), nullable=True
        ),
        sa.Column(
            "installation_suspended_at", sa.TIMESTAMP(timezone=True), nullable=True
        ),
        sa.Column("installation_suspended_by", sa.Integer(), nullable=True),
        sa.Column("installation_suspender", sa.UUID(), nullable=True),
        sa.Column(
            "installation_permissions",
            postgresql.JSONB(astext_type=sa.Text()),
            nullable=True,
        ),
        sa.Column("bio", sa.String(), nullable=True),
        sa.Column("pretty_name", sa.String(), nullable=True),
        sa.Column("company", sa.String(), nullable=True),
        sa.Column("blog", sa.String(), nullable=True),
        sa.Column("location", sa.String(), nullable=True),
        sa.Column("email", sa.String(), nullable=True),
        sa.Column("twitter_username", sa.String(), nullable=True),
        sa.Column("id", sa.UUID(), nullable=False),
        sa.Column("created_at", sa.TIMESTAMP(timezone=True), nullable=False),
        sa.Column("modified_at", sa.TIMESTAMP(timezone=True), nullable=True),
        sa.Column("deleted_at", sa.TIMESTAMP(timezone=True), nullable=True),
        sa.PrimaryKeyConstraint("id", name=op.f("external_organizations_pkey")),
        sa.UniqueConstraint(
            "external_id", name=op.f("external_organizations_external_id_key")
        ),
        sa.UniqueConstraint(
            "external_id", name=op.f("external_organizations_external_id_key")
        ),
        sa.UniqueConstraint(
            "installation_id", name=op.f("external_organizations_installation_id_key")
        ),
        sa.UniqueConstraint(
            "installation_id", name=op.f("external_organizations_installation_id_key")
        ),
        sa.UniqueConstraint(
            "name", "platform", name=op.f("external_organizations_name_platform_key")
        ),
        sa.UniqueConstraint("name", name=op.f("external_organizations_name_key")),
    )
    op.create_index(
        op.f("ix_external_organizations_created_at"),
        "external_organizations",
        ["created_at"],
        unique=False,
    )
    op.create_index(
        op.f("ix_external_organizations_deleted_at"),
        "external_organizations",
        ["deleted_at"],
        unique=False,
    )
    op.create_index(
        op.f("ix_external_organizations_modified_at"),
        "external_organizations",
        ["modified_at"],
        unique=False,
    )

    # Copy data from organizations to external_organizations
    op.execute(
        """
        INSERT INTO external_organizations (
            platform,
            name,
            external_id,
            avatar_url,
            is_personal,
            installation_id,
            installation_created_at,
            installation_updated_at,
            installation_suspended_at,
            installation_suspended_by,
            installation_suspender,
            installation_permissions,
            bio,
            pretty_name,
            company,
            blog,
            location,
            email,
            twitter_username,
            id,
            created_at,
            modified_at,
            deleted_at
        )
        SELECT
            platform,
            name,
            external_id,
            avatar_url,
            is_personal,
            installation_id,
            installation_created_at,
            installation_updated_at,
            installation_suspended_at,
            installation_suspended_by,
            installation_suspender,
            installation_permissions,
            bio,
            pretty_name,
            company,
            blog,
            location,
            email,
            twitter_username,
            id,
            created_at,
            modified_at,
            deleted_at
        FROM organizations;
        """
    )

    op.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";')

    # Generate a new ID
    op.add_column(
        "external_organizations",
        sa.Column("new_id", sa.UUID, nullable=True),
    )
    op.execute(
        """
        UPDATE external_organizations
        SET new_id = uuid_generate_v4();
        """
    )

    # Drop old foreign keys and update the ID

    op.drop_constraint(
        "issue_dependencies_organization_id_fkey",
        "issue_dependencies",
        type_="foreignkey",
    )
    op.execute(
        """
        UPDATE issue_dependencies
        SET organization_id = external_organizations.new_id
        FROM external_organizations
        WHERE issue_dependencies.organization_id = external_organizations.id;
        """
    )

    op.drop_constraint("issues_organization_id_fkey", "issues", type_="foreignkey")
    op.execute(
        """
        UPDATE issues
        SET organization_id = external_organizations.new_id
        FROM external_organizations
        WHERE issues.organization_id = external_organizations.id;
        """
    )

    op.drop_constraint(
        "pull_requests_organization_id_fkey", "pull_requests", type_="foreignkey"
    )
    op.execute(
        """
        UPDATE pull_requests
        SET organization_id = external_organizations.new_id
        FROM external_organizations
        WHERE pull_requests.organization_id = external_organizations.id;
        """
    )

    op.drop_constraint(
        "repositories_organization_id_fkey", "repositories", type_="foreignkey"
    )
    op.execute(
        """
        UPDATE repositories
        SET organization_id = external_organizations.new_id
        FROM external_organizations
        WHERE repositories.organization_id = external_organizations.id;
        """
    )

    op.drop_constraint("pledges_organization_id_fkey", "pledges", type_="foreignkey")
    op.execute(
        """
        UPDATE pledges
        SET organization_id = external_organizations.new_id
        FROM external_organizations
        WHERE pledges.organization_id = external_organizations.id;
        """
    )

    # Drop old ID and rename new_id to id
    op.drop_constraint(op.f("external_organizations_pkey"), "external_organizations")
    op.drop_column("external_organizations", "id")
    op.alter_column(
        "external_organizations",
        "new_id",
        new_column_name="id",
        nullable=False,
        existing_type=sa.UUID(),
        existing_nullable=True,
    )
    op.create_primary_key(
        op.f("external_organizations_pkey"), "external_organizations", ["id"]
    )

    # Create new foreign keys constraints
    op.create_foreign_key(
        op.f("issue_dependencies_organization_id_fkey"),
        "issue_dependencies",
        "external_organizations",
        ["organization_id"],
        ["id"],
    )
    op.create_foreign_key(
        op.f("issues_organization_id_fkey"),
        "issues",
        "external_organizations",
        ["organization_id"],
        ["id"],
    )
    op.create_foreign_key(
        op.f("pull_requests_organization_id_fkey"),
        "pull_requests",
        "external_organizations",
        ["organization_id"],
        ["id"],
    )
    op.create_foreign_key(
        op.f("repositories_organization_id_fkey"),
        "repositories",
        "external_organizations",
        ["organization_id"],
        ["id"],
    )
    op.create_foreign_key(
        op.f("pledges_organization_id_fkey"),
        "pledges",
        "external_organizations",
        ["organization_id"],
        ["id"],
    )

    # Drop sync-only organizations from organizations
    # Need to drop traffic recorded for these organizations
    op.execute(
        """
        DELETE FROM traffic
        WHERE organization_id IN (
            SELECT id FROM organizations
            WHERE installation_created_at IS NULL
            AND created_from_user_maintainer_upgrade IS FALSE
        );
        """
    )
    op.execute(
        """
        DELETE FROM organizations
        WHERE installation_created_at IS NULL
        AND created_from_user_maintainer_upgrade IS FALSE;
        """
    )

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###

    # Copy data from external_organizations to organizations
    op.execute(
        """
        INSERT INTO organizations (
            platform,
            name,
            external_id,
            avatar_url,
            is_personal,
            installation_id,
            installation_created_at,
            installation_updated_at,
            installation_suspended_at,
            installation_suspended_by,
            installation_suspender,
            installation_permissions,
            bio,
            pretty_name,
            company,
            blog,
            location,
            email,
            twitter_username,
            id,
            created_at,
            modified_at,
            deleted_at
        )
        SELECT
            platform,
            name,
            external_id,
            avatar_url,
            is_personal,
            installation_id,
            installation_created_at,
            installation_updated_at,
            installation_suspended_at,
            installation_suspended_by,
            installation_suspender,
            installation_permissions,
            bio,
            pretty_name,
            company,
            blog,
            location,
            email,
            twitter_username,
            id,
            created_at,
            modified_at,
            deleted_at
        FROM external_organizations
        WHERE external_organizations.external_id NOT IN (
            SELECT external_id FROM organizations
        );
        """
    )

    # Relink repositories, issues, pull_requests, issue_dependencies and pledges
    op.drop_constraint(
        op.f("repositories_organization_id_fkey"), "repositories", type_="foreignkey"
    )
    op.execute(
        """
        UPDATE repositories
        SET organization_id = organizations.id
        FROM organizations
        LEFT JOIN external_organizations ON external_organizations.external_id = organizations.external_id
        WHERE repositories.organization_id = external_organizations.id;
        """
    )
    op.create_foreign_key(
        "repositories_organization_id_fkey",
        "repositories",
        "organizations",
        ["organization_id"],
        ["id"],
    )

    op.drop_constraint(
        op.f("pull_requests_organization_id_fkey"), "pull_requests", type_="foreignkey"
    )
    op.execute(
        """
        UPDATE pull_requests
        SET organization_id = organizations.id
        FROM organizations
        LEFT JOIN external_organizations ON external_organizations.external_id = organizations.external_id
        WHERE pull_requests.organization_id = external_organizations.id;
        """
    )
    op.create_foreign_key(
        "pull_requests_organization_id_fkey",
        "pull_requests",
        "organizations",
        ["organization_id"],
        ["id"],
    )

    op.drop_constraint(
        op.f("issues_organization_id_fkey"), "issues", type_="foreignkey"
    )
    op.execute(
        """
        UPDATE issues
        SET organization_id = organizations.id
        FROM organizations
        LEFT JOIN external_organizations ON external_organizations.external_id = organizations.external_id
        WHERE issues.organization_id = external_organizations.id;
        """
    )
    op.create_foreign_key(
        "issues_organization_id_fkey",
        "issues",
        "organizations",
        ["organization_id"],
        ["id"],
    )

    op.drop_constraint(
        op.f("issue_dependencies_organization_id_fkey"),
        "issue_dependencies",
        type_="foreignkey",
    )
    op.execute(
        """
        UPDATE issue_dependencies
        SET organization_id = organizations.id
        FROM organizations
        LEFT JOIN external_organizations ON external_organizations.external_id = organizations.external_id
        WHERE issue_dependencies.organization_id = external_organizations.id;
        """
    )
    op.create_foreign_key(
        "issue_dependencies_organization_id_fkey",
        "issue_dependencies",
        "organizations",
        ["organization_id"],
        ["id"],
    )

    op.drop_constraint(
        op.f("pledges_organization_id_fkey"), "pledges", type_="foreignkey"
    )
    op.execute(
        """
        UPDATE pledges
        SET organization_id = organizations.id
        FROM organizations
        LEFT JOIN external_organizations ON external_organizations.external_id = organizations.external_id
        WHERE pledges.organization_id = external_organizations.id;
        """
    )
    op.create_foreign_key(
        "pledges_organization_id_fkey",
        "pledges",
        "organizations",
        ["organization_id"],
        ["id"],
    )

    op.drop_index(
        op.f("ix_external_organizations_modified_at"),
        table_name="external_organizations",
    )
    op.drop_index(
        op.f("ix_external_organizations_deleted_at"),
        table_name="external_organizations",
    )
    op.drop_index(
        op.f("ix_external_organizations_created_at"),
        table_name="external_organizations",
    )
    op.drop_table("external_organizations")
    # ### end Alembic commands ###
