import djclick as click
from django.conf import settings
from django.core.management import call_command
from django.db import connection, transaction


def reset_schema(db_config_user):
    sql_list = (
        "DROP  SCHEMA public CASCADE",
        f"CREATE SCHEMA public AUTHORIZATION {db_config_user}",
        "GRANT ALL ON SCHEMA public TO postgres",
        "GRANT ALL ON SCHEMA public TO public",
        "COMMENT ON SCHEMA public IS 'standard public schema';",
    )

    with transaction.atomic():
        with connection.cursor() as cursor:
            for sql in sql_list:
                cursor.execute(sql)


@click.command()
def command():
    user = settings.DATABASES["default"]["USER"]
    print(user)

    reset_schema(db_config_user=user)
    call_command("createcachetable")
    call_command("migrate")
    call_command("create_default_users")
    call_command("create_default_courses")
