from django.db import migrations
from django.contrib.auth.hashers import make_password

# Credenciales del dueño por defecto de la instalación Standalone.
# IMPORTANTE: cada cliente debe cambiarlas tras la instalación
# (o sobreescribirlas con las variables de entorno OWNER_EMAIL / OWNER_PASSWORD).
import os

DEFAULT_OWNER_EMAIL = os.environ.get('OWNER_EMAIL', 'luiscatalanaravena@gmail.com')
DEFAULT_OWNER_PASSWORD = os.environ.get('OWNER_PASSWORD', 'Lca212821?')
DEFAULT_BUSINESS_NAME = os.environ.get('BUSINESS_NAME', 'Mi Negocio')


def create_owner(apps, schema_editor):
    User = apps.get_model('accounts', 'User')
    Business = apps.get_model('scheduler', 'Business')

    # Instalación Standalone: un único negocio => un único dueño.
    if User.objects.filter(is_superuser=True).exists():
        return

    user, _ = User.objects.get_or_create(
        username=DEFAULT_OWNER_EMAIL,
        defaults={
            'email': DEFAULT_OWNER_EMAIL,
            'is_staff': True,
            'is_superuser': True,
            'is_active': True,
            'password': make_password(DEFAULT_OWNER_PASSWORD),
        },
    )

    Business.objects.get_or_create(
        user=user,
        defaults={'name': DEFAULT_BUSINESS_NAME},
    )


def remove_owner(apps, schema_editor):
    # Reversa no destructiva: no eliminamos datos del dueño.
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0001_initial'),
        ('scheduler', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(create_owner, remove_owner),
    ]
