"""
Fix the catalogue migrations
"""

from django.core.management.base import BaseCommand
from django.db import connection, transaction
from django.db.migrations import recorder

from ocyan.core.fender import config

STANDARD = [
    "0001_initial",
    "0002_auto_20150217_1221",
    "0003_data_migration_slugs",
    "0004_auto_20150217_1710",
    "0005_auto_20150604_1450",
    "0006_auto_20150807_1725",
    "0007_auto_20151207_1440",
    "0008_auto_20160304_1652",
    "0009_slugfield_noop",
    "0010_auto_20170420_0439",
    "0011_auto_20170422_1355",
    "0012_auto_20170609_1902",
    "0013_auto_20170821_1548",
    "0014_auto_20181115_1953",
    "0015_product_is_public",
    "0016_auto_20190327_0757",
    "0017_category_is_public",
    "0018_ocyan_additions",
]

TYPED = ["0019_auto_20190711_1230"]

PAID = ["0020_product_options_through", "0021_auto_20190711_1244"]


class Command(BaseCommand):
    help = __doc__

    def add_arguments(self, parser):
        parser.add_argument("--no-dry-run", action="store_true")

    def migration_names(self):
        # pylint: disable=no-member
        if "ocyan.plugin.oscar_paid_product_options" in config.ocyan_plugins:
            return STANDARD + TYPED + PAID
        elif "ocyan.plugin.oscar_typed_product_options" in config.ocyan_plugins:
            return STANDARD + TYPED
        return STANDARD

    def handle(self, *args, **options):
        rec = recorder.MigrationRecorder(connection)
        rec.ensure_schema()
        is_up_to_date = True
        for name in STANDARD:
            is_up_to_date = (
                is_up_to_date
                and rec.migration_qs.filter(app="catalogue").filter(name=name).exists()
            )

        if is_up_to_date:
            self.stdout.write(
                self.style.SUCCESS(
                    "No need to mess with migration history, it is all good"
                )
            )
        else:
            with transaction.atomic():
                self.stdout.write(
                    self.style.WARNING(
                        "Migrations need fixing, deleting all migrations"
                    )
                )
                rec.migration_qs.filter(app="catalogue").delete()
                self.stdout.write(self.style.WARNING("Writing new migrations"))
                for name in self.migration_names():
                    rec.migration_qs.create(app="catalogue", name=name)
                if not options[
                    "no_dry_run"
                ]:  # rollback everything because it waS DRY RUN LOL
                    self.stdout.write(
                        self.style.ERROR("Rolling back import because of dry run.")
                    )
                    transaction.set_rollback(True)
