""" Recipes locked migration: from settings to user locks """
from typing import cast

import peewee as pw
from peewee_migrate import Migrator
import logging
from peewee import IntegrityError

from atxdispatch import settings
from atxdispatch.dispatch import load_setup


def move_config_table_locks_to_db(migrator: Migrator) -> None:
    User = cast('model.User', migrator.orm['user'])
    LockedTable = cast('model.LockedTable', migrator.orm['lockedtable'])

    if load_setup(settings.CONFIG_FILE).get("recipes_locked"):
        logging.info("Found recipes_locked configuration, migrating to UserLocks")

        for user in User.select():
            try:
                LockedTable(user=user, table_name="Recipe").save()
                logging.info(f"Added user lock for {user.username}")
            except IntegrityError:
                logging.info(f"User lock for {user.username} exists, skipping")


def migrate(migrator: Migrator, database: pw.Database, *, fake: bool = False) -> None:
    migrator.run(move_config_table_locks_to_db, migrator)


def rollback(migrator: Migrator, database: pw.Database, *, fake: bool = False) -> None:
    pass
