"""
Legacy MySQL already has `users`, `permissions`, `roles`, `sessions`, etc. from FastAPI.

After `migrate accounts 0001 --fake`, Django never ran the CREATE / AddField SQL. This
migration adds Django-only columns on `users` and creates auth M2M tables if missing.

Table names match sqlmigrate for accounts.0001 with db_table = users:
  - users_groups
  - users_user_permissions
"""

from django.db import migrations


def _mysql_add_column_if_missing(cursor, table: str, column: str, definition_sql: str) -> None:
    cursor.execute(
        """
        SELECT COUNT(*) FROM information_schema.columns
        WHERE table_schema = DATABASE() AND table_name = %s AND column_name = %s
        """,
        [table, column],
    )
    if cursor.fetchone()[0] == 0:
        cursor.execute(f"ALTER TABLE `{table}` ADD COLUMN `{column}` {definition_sql}")


def _mysql_table_exists(cursor, table: str) -> bool:
    cursor.execute(
        """
        SELECT COUNT(*) FROM information_schema.tables
        WHERE table_schema = DATABASE() AND table_name = %s
        """,
        [table],
    )
    return cursor.fetchone()[0] > 0


def forwards_mysql(apps, schema_editor):
    connection = schema_editor.connection
    if connection.vendor != "mysql":
        return
    with connection.cursor() as cursor:
        _mysql_add_column_if_missing(cursor, "users", "last_login", "DATETIME(6) NULL")
        _mysql_add_column_if_missing(cursor, "users", "is_superuser", "TINYINT(1) NOT NULL DEFAULT 0")
        _mysql_add_column_if_missing(cursor, "users", "is_active", "TINYINT(1) NOT NULL DEFAULT 1")
        _mysql_add_column_if_missing(cursor, "users", "is_staff", "TINYINT(1) NOT NULL DEFAULT 0")

        if not _mysql_table_exists(cursor, "users_groups"):
            cursor.execute(
                """
                CREATE TABLE `users_groups` (
                  `id` bigint NOT NULL AUTO_INCREMENT,
                  `user_id` bigint NOT NULL,
                  `group_id` int NOT NULL,
                  PRIMARY KEY (`id`),
                  UNIQUE KEY `users_groups_user_id_group_id_fc7788e8_uniq` (`user_id`, `group_id`),
                  KEY `users_groups_user_id_f500bee5` (`user_id`),
                  KEY `users_groups_group_id_2f3517aa` (`group_id`),
                  CONSTRAINT `users_groups_user_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
                  CONSTRAINT `users_groups_group_id_fk` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                """
            )

        if not _mysql_table_exists(cursor, "users_user_permissions"):
            cursor.execute(
                """
                CREATE TABLE `users_user_permissions` (
                  `id` bigint NOT NULL AUTO_INCREMENT,
                  `user_id` bigint NOT NULL,
                  `permission_id` int NOT NULL,
                  PRIMARY KEY (`id`),
                  UNIQUE KEY `users_user_permissions_user_id_permission_id_3b86cbdf_uniq` (`user_id`, `permission_id`),
                  KEY `users_user_permissions_user_id_92473840` (`user_id`),
                  KEY `users_user_permissions_permission_id_6d08dcd2` (`permission_id`),
                  CONSTRAINT `users_user_permissions_user_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
                  CONSTRAINT `users_user_permissions_permission_id_fk` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                """
            )


def backwards_mysql(apps, schema_editor):
    # Non-destructive: do not drop legacy tables or columns.
    pass


class Migration(migrations.Migration):

    dependencies = [
        ("accounts", "0001_initial"),
    ]

    operations = [
        migrations.RunPython(forwards_mysql, backwards_mysql),
    ]
