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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SCRIPT="$ROOT_DIR/scripts/s06-preflight.sh"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

pass() {
  printf 'PASS: %s\n' "$1"
}

fail() {
  printf 'FAIL: %s\n' "$1" >&2
  exit 1
}

run_expect_failure() {
  local name="$1"
  local expected="$2"
  shift 2
  local stdout_file="$TMP_DIR/${name}.out"
  local stderr_file="$TMP_DIR/${name}.err"

  set +e
  "$@" >"$stdout_file" 2>"$stderr_file"
  local exit_code=$?
  set -e

  if [[ $exit_code -eq 0 ]]; then
    printf 'stdout:\n' >&2
    cat "$stdout_file" >&2
    printf '\nstderr:\n' >&2
    cat "$stderr_file" >&2
    fail "${name} unexpectedly succeeded"
  fi

  if ! grep -Fq "$expected" "$stderr_file" && ! grep -Fq "$expected" "$stdout_file"; then
    printf 'stdout:\n' >&2
    cat "$stdout_file" >&2
    printf '\nstderr:\n' >&2
    cat "$stderr_file" >&2
    fail "${name} did not contain expected text: ${expected}"
  fi

  pass "$name"
}

run_expect_failure api_down "Start the API from JobTrackerApi/ with 'dotnet run'" env API_BASE="http://127.0.0.1:59999/api" bash "$SCRIPT"
run_expect_failure wrong_api_base "Start the API from JobTrackerApi/ with 'dotnet run'" env API_BASE="http://localhost:1/api" bash "$SCRIPT"

SERVER_LOG="$TMP_DIR/mock.log"
python3 - <<'PY' >"$SERVER_LOG" 2>&1 &
import http.server
import json
import socketserver

class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/api/auth/config':
            payload = {
                'requireAuth': True,
                'googleEnabled': True,
                'localEnabled': True,
                'allowRegistration': False,
            }
            body = json.dumps(payload).encode('utf-8')
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Content-Length', str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return

        if self.path == '/api/admin/system':
            body = b'{not-json\n'
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Content-Length', str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return

        self.send_response(404)
        self.end_headers()

    def log_message(self, fmt, *args):
        return

with socketserver.TCPServer(('127.0.0.1', 59998), Handler) as httpd:
    httpd.serve_forever()
PY
SERVER_PID=$!
trap 'kill "$SERVER_PID" >/dev/null 2>&1 || true; rm -rf "$TMP_DIR"' EXIT
sleep 1
run_expect_failure malformed_json "Malformed JSON returned by API." env API_BASE="http://127.0.0.1:59998/api" bash "$SCRIPT"
kill "$SERVER_PID" >/dev/null 2>&1 || true
wait "$SERVER_PID" 2>/dev/null || true

pass "all preflight negative tests"
