#!/usr/bin/env bash
# mail-switch.sh — toggle between Mailpit (local testing) and real SMTP server
# Usage: ./scripts/mail-switch.sh [mailpit|real]
#        Without argument: auto-detects current mode and toggles

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_DIR="$(dirname "$SCRIPT_DIR")"
ENV_FILE="$APP_DIR/.env"
REAL_ENV="$SCRIPT_DIR/mail-real.env"

if [[ ! -f "$ENV_FILE" ]]; then
    echo "ERROR: .env file not found at $ENV_FILE"
    exit 1
fi

if [[ ! -f "$REAL_ENV" ]]; then
    echo "ERROR: mail-real.env not found at $REAL_ENV"
    echo "Create it with your real SMTP settings."
    exit 1
fi

# Read current MAIL_HOST from .env
current_host=$(grep -E "^MAIL_HOST=" "$ENV_FILE" | cut -d= -f2 | tr -d '"' | tr -d "'")

# Determine target mode
if [[ "${1:-}" == "mailpit" ]]; then
    target="mailpit"
elif [[ "${1:-}" == "real" ]]; then
    target="real"
elif [[ "$current_host" == "localhost" || "$current_host" == "127.0.0.1" ]]; then
    target="real"
    echo "Current mode: Mailpit → switching to real SMTP"
else
    target="mailpit"
    echo "Current mode: real SMTP ($current_host) → switching to Mailpit"
fi

set_env_value() {
    local key="$1"
    local value="$2"
    # Replace the key=value line in .env (handles empty values too)
    sed -i "s|^${key}=.*|${key}=${value}|" "$ENV_FILE"
}

if [[ "$target" == "mailpit" ]]; then
    set_env_value "MAIL_MAILER"    "smtp"
    set_env_value "MAIL_HOST"      "localhost"
    set_env_value "MAIL_PORT"      "1025"
    set_env_value "MAIL_USERNAME"  ""
    set_env_value "MAIL_PASSWORD"  ""
    set_env_value "MAIL_ENCRYPTION" "null"
    echo "Mail switched to: Mailpit (localhost:1025)"
else
    # Load real SMTP settings from mail-real.env
    while IFS='=' read -r key value; do
        # Skip comments and empty lines
        [[ "$key" =~ ^#.*$ || -z "$key" ]] && continue
        set_env_value "$key" "$value"
    done < "$REAL_ENV"
    real_host=$(grep -E "^MAIL_HOST=" "$REAL_ENV" | cut -d= -f2)
    echo "Mail switched to: real SMTP ($real_host)"
fi

# Clear config cache and restart queue workers
cd "$APP_DIR"
php artisan config:clear
php artisan queue:restart
echo "Done. Config cleared and queue workers restarted."
