#!/bin/bash

# Asegurar que el script se ejecute desde el directorio del proyecto
cd "$(dirname "$0")"

# Usa el intérprete del entorno virtual ACTIVO (el script se ejecuta con el venv ya activado).
LOCAL_VENV="./.venv/bin/python"

if [ -n "$VIRTUAL_ENV" ] && [ -x "$VIRTUAL_ENV/bin/python" ]; then
    PYTHON_VENV="$VIRTUAL_ENV/bin/python"
elif [ -f "$LOCAL_VENV" ]; then
    PYTHON_VENV="$LOCAL_VENV"
else
    echo "Error: No hay entorno virtual activo ni entorno local."
    echo "Activá el venv antes de ejecutar (source <ruta_venv>/bin/activate) o creá ./.venv."
    exit 1
fi

# Nombre del entorno virtual: se muestra la ruta relativa (ej. tienda/lumi/3.9)
VENV_NAME="(entorno local ./.venv)"
if [ -n "$VIRTUAL_ENV" ]; then
    if [[ "$VIRTUAL_ENV" == *"/virtualenv/"* ]]; then
        VENV_NAME="${VIRTUAL_ENV##*/virtualenv/}"
    else
        VENV_NAME="$(basename "$VIRTUAL_ENV")"
    fi
fi

echo "--------------------------------------------------"
echo "  INICIALIZACIÓN DE BASE DE DATOS (PRODUCCIÓN)"
echo "--------------------------------------------------"
echo ""
echo " Entorno virtual: $VENV_NAME"
echo " Intérprete:      $PYTHON_VENV"
echo ""
printf "¿Confirmás que es el entorno correcto y continuar? [s/N]: "
read -r CONFIRMA
if [[ ! "$CONFIRMA" =~ ^[sS]$ ]]; then
    echo "Cancelado."
    exit 1
fi
echo ""

# 1. Generar migraciones pendientes
echo "[1/5] Generando migraciones..."
$PYTHON_VENV manage.py makemigrations --noinput
if [ $? -ne 0 ]; then
    echo "Error al generar migraciones."
    exit 1
fi
echo "      Ok."

# 2. Ejecutar migraciones (crea el esquema si la base es nueva o lo deja al día)
echo "[2/5] Ejecutando migrate..."
$PYTHON_VENV manage.py migrate
if [ $? -ne 0 ]; then
    echo "Error al ejecutar las migraciones."
    exit 1
fi
echo "      Ok."

# 3. Vaciar todos los datos y resetear los id/secuencias (sin borrar el esquema)
echo "[3/5] Vaciamos y reseteamos la base (flush)..."
$PYTHON_VENV manage.py flush --noinput
if [ $? -ne 0 ]; then
    echo "Error al vaciar la base de datos."
    exit 1
fi
echo "      Ok."

# 4. Crear los usuarios de producción
echo "[4/5] Creando usuarios de producción..."
$PYTHON_VENV manage.py shell <<'EOF'
from django.contrib.auth.models import User

# APP Usuario Union - máximo nivel Sistemas (superuser y staff)
u, created = User.objects.get_or_create(username='unionjht_unionsi')
u.first_name = 'UnionSI'
u.last_name = 'UnionSI'
u.email = 'unionsi@tienda.com.ar'
u.is_staff = True
u.is_superuser = True
u.is_active = True
u.set_password('Usi@81416141')
u.save()
print(('Creado' if created else 'Actualizado'), '-> unionjht_unionsi (superuser)')

# APP Usuario Admin - para que el cliente administre (staff, sin superuser)
a, created = User.objects.get_or_create(username='admin@tienda.com.ar')
a.first_name = 'Admin'
a.last_name = 'Admin'
a.email = 'admin@tienda.com.ar'
a.is_staff = True
a.is_superuser = False
a.is_active = True
a.set_password('Admin@123')
a.save()
print(('Creado' if created else 'Actualizado'), '-> admin@tienda.com.ar (staff)')
EOF

if [ $? -ne 0 ]; then
    echo "Error al crear los usuarios."
    exit 1
fi
echo "      Ok."

# 5. Recopilar archivos estáticos
echo "[5/5] Recopilando archivos estáticos (collectstatic)..."
$PYTHON_VENV manage.py collectstatic --noinput
if [ $? -ne 0 ]; then
    echo "Error al recopilar archivos estáticos."
    exit 1
fi
echo "      Ok."

echo "--------------------------------------------------"
echo "¡PROCESO COMPLETADO EXITOSAMENTE!"
echo " Usuario Union:  (superuser / staff)"
echo " Usuario Admin:  admin@tienda.com.ar  (staff)"
echo "--------------------------------------------------"
