#!/usr/bin/env bash
set -euo pipefail

FRONTEND_DIR="${FRONTEND_DIR:-sociowire-frontend}"
FILE="$FRONTEND_DIR/src/auth/AuthContext.jsx"

if [ ! -f "$FILE" ]; then
  echo "ERROR: not found: $FILE"
  exit 1
fi

echo "[1/3] Backup AuthContext.jsx"
cp -a "$FILE" "$FILE.bak.$(date +%s)"

echo "[2/3] Remove direct Keycloak constants (KC_BASE/KC_REALM/KC_CLIENT_ID) if present"
# delete block lines that define KC_BASE/KC_REALM/KC_CLIENT_ID
sed -i \
  -e '/^const KC_BASE = /d' \
  -e '/^const KC_REALM = /d' \
  -e '/^const KC_CLIENT_ID = /d' \
  "$FILE"

echo "[3/3] Replace refreshWithKeycloak + login() to use backend /api/login + /api/refresh"

# Replace function refreshWithKeycloak(...) { ... } with refreshViaBackend(...)
perl -0777 -i -pe '
s/async function refreshWithKeycloak\([^\)]*\)\s*\{.*?\n\}\n/async function refreshViaBackend(refreshToken) {\n  const res = await fetch(\"\/api\/refresh\", {\n    method: \"POST\",\n    headers: { \"Content-Type\": \"application\/json\" },\n    credentials: \"include\",\n    body: JSON.stringify({ refresh_token: refreshToken }),\n  });\n\n  const text = await res.text();\n  if (!res.ok) {\n    let msg = text;\n    try {\n      const j = JSON.parse(text);\n      msg = j.error_description || j.error || text;\n    } catch {}\n    throw new Error(`${res.status} ${msg}`);\n  }\n\n  const data = JSON.parse(text);\n  if (!data.access_token) throw new Error(\"No access_token in refresh response\");\n  return {\n    accessToken: data.access_token,\n    refreshToken: data.refresh_token || refreshToken,\n  };\n}\n/sms
' "$FILE"

# Replace any calls to refreshWithKeycloak( with refreshViaBackend(
sed -i 's/refreshWithKeycloak(/refreshViaBackend(/g' "$FILE"

# Replace login() body to call /api/login
perl -0777 -i -pe '
s/async function login\([^\)]*\)\s*\{.*?\n\s*\}\n\n\s*function logout\(/async function login(user, pass) {\n    setLastError(\"\");\n    const u = (user || \"\").trim();\n    if (!u || !pass) {\n      setLastError(\"Username and password required.\");\n      return;\n    }\n\n    try {\n      setLoading(true);\n\n      const res = await fetch(\"\/api\/login\", {\n        method: \"POST\",\n        headers: { \"Content-Type\": \"application\/json\" },\n        credentials: \"include\",\n        body: JSON.stringify({ username: u, password: pass }),\n      });\n\n      const text = await res.text();\n      if (!res.ok) {\n        let msg = \"Invalid credentials or auth error.\";\n        try {\n          const j = JSON.parse(text);\n          msg = j.error_description || j.error || msg;\n        } catch {}\n        clearAuth(`${res.status} ${msg}`);\n        return;\n      }\n\n      const data = JSON.parse(text);\n      const accessToken = data.access_token;\n      const refreshToken = data.refresh_token;\n\n      if (!accessToken) {\n        clearAuth(\"No access token in response.\");\n        return;\n      }\n\n      persistAuth({ accessToken, refreshToken, user: u });\n      setLastError(\"\");\n    } catch (e) {\n      console.error(\"[AUTH] network error\", e);\n      clearAuth(\"Network error during login.\");\n    } finally {\n      setLoading(false);\n    }\n  }\n\n  function logout(/sms
' "$FILE"

echo "DONE frontend patch."
