from django.core.management.base import BaseCommand
from django.db import connection
from django.db.models import Max

from ocyan.plugin.oscar_sequential_order_numbers.models import Sequence


class Command(BaseCommand):
    help = "Set the latest generated order number"

    def add_arguments(self, parser):
        parser.add_argument("order_number", type=int)

    def handle(self, *args, **options):
        current_max = Sequence.objects.all().aggregate(Max("id"))["id__max"] or 0
        if current_max >= options["order_number"]:
            self.stdout.write(
                self.style.ERROR(
                    f"Value {options['order_number']} is not higher than the current max of {current_max}"
                )
            )
        else:
            obj = Sequence.objects.create(id=options["order_number"])
            if connection.vendor == "postgresql":
                with connection.cursor() as cursor:
                    cursor.execute(
                        """
                            BEGIN;
                            SELECT setval(pg_get_serial_sequence('"ocyan_plugin_oscar_sequential_order_numbers_sequence"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "ocyan_plugin_oscar_sequential_order_numbers_sequence";
                            COMMIT;
                        """
                    )
            self.stdout.write(
                self.style.SUCCESS(f"Set latest order number to {obj.id}")
            )
