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


class Command(BaseCommand):
    help = "Rename legacy soil_data tables to location_data tables when needed"

    def handle(self, *args, **options):
        table_map = {
            "soil_data_soillocation": "location_data_soillocation",
            "soil_data_soildepthdata": "location_data_soildepthdata",
        }

        existing_tables = set(connection.introspection.table_names())
        renamed: list[str] = []

        with connection.cursor() as cursor:
            for old_name, new_name in table_map.items():
                if new_name in existing_tables:
                    continue
                if old_name not in existing_tables:
                    continue

                cursor.execute(f"RENAME TABLE `{old_name}` TO `{new_name}`")
                renamed.append(f"{old_name} -> {new_name}")
                existing_tables.discard(old_name)
                existing_tables.add(new_name)

        if renamed:
            self.stdout.write(
                self.style.SUCCESS("Renamed legacy tables: " + ", ".join(renamed))
            )
            return

        self.stdout.write("No legacy location_data tables needed repair.")
