"""
Management command to create Sites for all tenants that don't have one.
This backfills existing tenants created before the auto-creation signal was added.
"""
from django.core.management.base import BaseCommand
from smoothschedule.identity.core.models import Tenant
from smoothschedule.platform.tenant_sites.models import Site


class Command(BaseCommand):
    help = 'Create Sites (with default home pages) for all tenants that do not have one'

    def handle(self, *args, **options):
        # Get all non-public tenants
        tenants = Tenant.objects.exclude(schema_name='public')
        created_count = 0
        skipped_count = 0

        for tenant in tenants:
            if Site.objects.filter(tenant=tenant).exists():
                self.stdout.write(f'Skipping {tenant.name} - Site already exists')
                skipped_count += 1
            else:
                self.stdout.write(f'Creating Site for {tenant.name}...')
                # Site.post_save signal will auto-create default home page
                Site.objects.create(tenant=tenant, is_enabled=True)
                created_count += 1

        self.stdout.write(
            self.style.SUCCESS(
                f'Created {created_count} new Sites. Skipped {skipped_count} tenants with existing Sites.'
            )
        )
