"""
Script to ensure production domain exists in the database.
Run with: python manage.py shell < scripts/ensure_production_domain.py
"""
from smoothschedule.identity.core.models import Tenant, Domain
from django.conf import settings

def ensure_production_domain():
    # Get or create the public tenant
    public_tenant, created = Tenant.objects.get_or_create(
        schema_name='public',
        defaults={
            'name': 'Public Tenant',
            'subscription_tier': 'PROFESSIONAL', # Default tier
        }
    )
    if created:
        print(f"Created public tenant: {public_tenant.name}")
    else:
        print(f"Found public tenant: {public_tenant.name}")

    # Check for smoothschedule.com domain
    domain_name = 'smoothschedule.com'
    domain, created = Domain.objects.get_or_create(
        domain=domain_name,
        defaults={
            'tenant': public_tenant,
            'is_primary': True,
        }
    )

    if created:
        print(f"Created domain: {domain.domain}")
    else:
        print(f"Domain already exists: {domain.domain}")
        # Ensure it points to public tenant
        if domain.tenant != public_tenant:
            print(f"WARNING: Domain {domain.domain} points to tenant {domain.tenant.schema_name}, expected public!")
            
    # Also check for www.smoothschedule.com
    www_domain_name = 'www.smoothschedule.com'
    www_domain, www_created = Domain.objects.get_or_create(
        domain=www_domain_name,
        defaults={
            'tenant': public_tenant,
            'is_primary': False,
        }
    )
    
    if www_created:
        print(f"Created domain: {www_domain.domain}")
    else:
        print(f"Domain already exists: {www_domain.domain}")

ensure_production_domain()
