"""Add project_url to GitProject

Revision ID: f0abb806c3d4
Revises: c6250555a36c
Create Date: 2020-04-27 11:46:17.288814

"""
from typing import TYPE_CHECKING

import sqlalchemy as sa
from alembic import op
from sqlalchemy import Column, Integer, String, orm
from sqlalchemy.ext.declarative import declarative_base

# revision identifiers, used by Alembic.
revision = "f0abb806c3d4"
down_revision = "c6250555a36c"
branch_labels = None
depends_on = None

# https://github.com/python/mypy/issues/2477#issuecomment-313984522 ^_^
if TYPE_CHECKING:
    Base = object
else:
    Base = declarative_base()


class GitProjectUpgradeModel(Base):
    __tablename__ = "git_projects"
    id = Column(Integer, primary_key=True)
    namespace = Column(String, index=True)
    repo_name = Column(String, index=True)
    project_url = Column(String)

    def __repr__(self):
        return (
            f"GitProjectUpgradeModel(name={self.namespace}/{self.repo_name}, "
            f"project_url={self.project_url})"
        )

    def __str__(self):
        return self.__repr__()


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("git_projects", sa.Column("project_url", sa.String(), nullable=True))
    # ### end Alembic commands ###

    bind = op.get_bind()
    session = orm.Session(bind=bind)

    for project in session.query(GitProjectUpgradeModel).all():
        if not project.project_url:
            project.project_url = (
                f"https://github.com/{project.namespace}/{project.repo_name}"
            )
            session.add(project)

    session.commit()


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("git_projects", "project_url")
    # ### end Alembic commands ###
