#!/bin/bash
# Alterna entre auth local (sin Keycloak/Hub) y auth workspace.
#
# Uso:
#   ./auth-mode.sh              → muestra modo actual
#   ./auth-mode.sh local        → activa login local sin workspace
#   ./auth-mode.sh workspace    → configura y activa conexión con workspace

set -e

# Siempre operar sobre el .env en la raíz del proyecto (un nivel arriba de scripts/)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
cd "$PROJECT_ROOT"

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
RED='\033[0;31m'
BOLD='\033[1m'
NC='\033[0m'

ENV_FILE=".env"

# ── Helpers ────────────────────────────────────────────────────────────────────

get_env() {
    grep -E "^${1}=" "$ENV_FILE" 2>/dev/null | cut -d'=' -f2- | tr -d '"' | tr -d "'"
}

set_env() {
    local key="$1" value="$2"
    if grep -qE "^${key}=" "$ENV_FILE" 2>/dev/null; then
        sed -i "s|^${key}=.*|${key}=${value}|" "$ENV_FILE"
    else
        echo "${key}=${value}" >> "$ENV_FILE"
    fi
}

ask() {
    # ask "Pregunta" "default" → imprime en stderr, devuelve valor por stdout
    local prompt="$1" default="$2" answer
    echo -en "${CYAN}  ${prompt}${default:+ [${default}]}: ${NC}" >&2
    read -r answer
    echo "${answer:-$default}"
}

restart_services() {
    echo ""
    echo -en "${YELLOW}  ¿Reiniciar backend y frontend ahora? [S/n]: ${NC}"
    read -r ans
    if [[ "${ans,,}" != "n" ]]; then
        echo -e "${BLUE}  Reiniciando servicios...${NC}"
        docker compose up -d --force-recreate backend frontend
        echo -e "${GREEN}  ✓ Listo — espera unos segundos a que levanten.${NC}"
    else
        echo -e "${YELLOW}  Reinicia manualmente cuando estés listo:${NC}"
        echo -e "  ${BLUE}docker compose up -d --force-recreate backend frontend${NC}"
    fi
}

# check_url "Etiqueta" "url" → HEAD/GET con timeout corto; reporta OK / código / sin respuesta
check_url() {
    local label="$1" url="$2"
    if [ -z "$url" ]; then
        echo -e "  ${YELLOW}∅${NC} ${label}: sin URL configurada"
        return
    fi
    local code
    code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 --max-time 8 "$url" 2>/dev/null || echo "000")
    if [ "$code" = "000" ]; then
        echo -e "  ${RED}✗${NC} ${label}: sin respuesta (${url})"
    elif [ "$code" -ge 200 ] && [ "$code" -lt 500 ]; then
        echo -e "  ${GREEN}✓${NC} ${label}: responde (HTTP ${code})"
    else
        echo -e "  ${YELLOW}!${NC} ${label}: HTTP ${code} (${url})"
    fi
}

# Valida conectividad al Hub y Keycloak desde la máquina host.
validate_workspace_connection() {
    local hub="$1" kc="$2" realm="$3"
    echo ""
    echo -e "${BOLD}  Validando conexión al workspace...${NC}"
    echo -e "${BLUE}  ──────────────────────────────────────${NC}"

    # Hub: probar la raíz pública
    check_url "Hub" "${hub%/}"

    # Keycloak: el endpoint OIDC well-known del realm confirma que el realm existe
    local realm_name="${realm:-master}"
    check_url "Keycloak (realm ${realm_name})" "${kc%/}/realms/${realm_name}/.well-known/openid-configuration"

    echo -e "${BLUE}  ──────────────────────────────────────${NC}"
    echo -e "  ${YELLOW}Recordatorio:${NC} validar conexión no equivale a estar registrado."
    echo -e "  Para entrar desde el workspace, el equipo del Hub debe:"
    echo -e "    • Registrar esta app en el Hub (App Launcher)."
    echo -e "    • Agregar tu redirect URI en el client de Keycloak:"
    echo -e "      ${BLUE}<URL pública de esta app>/auth/callback${NC}"
}

# ── Crear .env si no existe ────────────────────────────────────────────────────

if [ ! -f "$ENV_FILE" ]; then
    [ -f ".env.example" ] && cp .env.example "$ENV_FILE" || touch "$ENV_FILE"
    echo -e "${GREEN}✓ .env creado${NC}"
fi

# ── Estado actual ──────────────────────────────────────────────────────────────

current_local=$(get_env "DEV_LOCAL_AUTH")
is_local=$([[ "${current_local,,}" == "true" ]] && echo "yes" || echo "no")

show_status() {
    echo ""
    if [ "$is_local" = "yes" ]; then
        echo -e "  ${BOLD}Modo:${NC}       ${YELLOW}LOCAL${NC} (sin Keycloak/Hub)"
        echo -e "  ${BOLD}Acceso:${NC}     ${BLUE}http://localhost:5173/login${NC} → 'Entrar como dev'"
    else
        local ws=$(get_env "WORKSPACE_URL")
        local client=$(get_env "KEYCLOAK_CLIENT_ID")
        echo -e "  ${BOLD}Modo:${NC}       ${GREEN}WORKSPACE${NC} (Keycloak + Hub)"
        echo -e "  ${BOLD}Workspace:${NC}  ${ws:-no configurado}"
        echo -e "  ${BOLD}Keycloak:${NC}   ${ws:+${ws}/kcauth} (realm $(get_env KEYCLOAK_REALM), client ${client:-?})"
    fi
    echo ""
}

# ── Comando ────────────────────────────────────────────────────────────────────

MODE="${1:-status}"

case "$MODE" in

# ── LOCAL ──────────────────────────────────────────────────────────────────────
    local)
        echo -e "\n${BOLD}Activando modo LOCAL${NC}"
        echo -e "${YELLOW}──────────────────────────────────────────${NC}"

        set_env "DEV_LOCAL_AUTH" "True"
        is_local="yes"

        # SECRET_KEY — necesario para firmar el JWT local
        current_key=$(get_env "SECRET_KEY")
        if [ -z "$current_key" ] || [ "$current_key" = "change-this-secret-key-in-production" ]; then
            secret=$(openssl rand -hex 32 2>/dev/null || echo "dev-$(date +%s | md5sum | head -c 32)")
            set_env "SECRET_KEY" "$secret"
            echo -e "  ${GREEN}✓${NC} SECRET_KEY generado"
        fi

        # BACKEND_URL — URL interna del backend para que el frontend llame al dev-login
        current_backend=$(get_env "BACKEND_URL")
        if [ -z "$current_backend" ]; then
            set_env "BACKEND_URL" "http://backend:8000"
            echo -e "  ${GREEN}✓${NC} BACKEND_URL=http://backend:8000"
        fi

        echo -e "  ${GREEN}✓${NC} DEV_LOCAL_AUTH=True"
        show_status
        restart_services
        ;;

# ── WORKSPACE ─────────────────────────────────────────────────────────────────
    workspace)
        echo -e "\n${BOLD}Configurando modo WORKSPACE${NC}"
        echo -e "${BLUE}──────────────────────────────────────────${NC}"
        echo -e "  Hub y Keycloak se derivan de WORKSPACE_URL."
        echo -e "  Presiona Enter para mantener el valor actual.\n"

        # Las dos únicas preguntas necesarias:
        current_ws=$(get_env "WORKSPACE_URL")
        ws_url=$(ask "URL del workspace" "${current_ws:-https://workspace.aduanasoft.com}")
        ws_url="${ws_url%/}"

        current_realm=$(get_env "KEYCLOAK_REALM")
        kc_realm=$(ask "Keycloak Realm" "${current_realm:-master}")

        current_client=$(get_env "KEYCLOAK_CLIENT_ID")
        kc_client=$(ask "Keycloak Client ID" "${current_client:-app-frontend}")

        echo ""
        echo -e "${BLUE}  Aplicando configuración...${NC}"

        set_env "WORKSPACE_URL"      "$ws_url"
        set_env "KEYCLOAK_REALM"     "$kc_realm"
        set_env "KEYCLOAK_CLIENT_ID" "$kc_client"
        set_env "DEV_LOCAL_AUTH"     "False"
        is_local="no"

        echo -e "  ${GREEN}✓${NC} Configuración guardada en .env"

        # Validar conectividad (Hub = WORKSPACE_URL, Keycloak = WORKSPACE_URL/kcauth)
        validate_workspace_connection "$ws_url" "${ws_url}/kcauth" "$kc_realm"

        show_status
        restart_services
        ;;

# ── STATUS ─────────────────────────────────────────────────────────────────────
    status|"")
        echo -e "${BOLD}[auth-mode] Estado actual${NC}"
        show_status
        echo "Comandos:"
        echo -e "  ${GREEN}./auth-mode.sh local${NC}      → Login local, sin workspace"
        echo -e "  ${GREEN}./auth-mode.sh workspace${NC}  → Configurar y conectar al workspace"
        echo ""
        ;;

    *)
        echo -e "${RED}Uso: $0 [local|workspace|status]${NC}"
        exit 1
        ;;
esac
