#!/bin/bash

API_URL="${API_URL:-https://gantt-board.twisteddevices.com/api}"
COOKIE_FILE="${GANTT_COOKIE_FILE:-$HOME/.config/gantt-board/cookies.txt}"

ensure_cookie_store() {
  mkdir -p "$(dirname "$COOKIE_FILE")"
  touch "$COOKIE_FILE"
}

urlencode() {
  jq -rn --arg v "$1" '$v|@uri'
}

login_if_needed() {
  ensure_cookie_store

  # Check if we have a valid session by making a test request
  if ! api_call_raw GET "/auth/session" >/dev/null 2>&1; then
    echo "Session expired, logging in..." >&2

    local email="${GANTT_EMAIL:-mbruce+max@topdoglabs.com}"
    local password="${GANTT_PASSWORD:-!7883Gantt}"

    local login_data
    login_data=$(jq -n --arg email "$email" --arg password "$password" '{email: $email, password: $password, rememberMe: true}')

    local login_response
    login_response=$(curl -sS -w "\n%{http_code}" -X POST "${API_URL}/auth/login" \
      -H "Content-Type: application/json" \
      --data "$login_data" \
      -c "$COOKIE_FILE" -b "$COOKIE_FILE") || return 1

    local http_code
    http_code=$(echo "$login_response" | tail -n1)
    local body
    body=$(echo "$login_response" | sed '$d')

    if [[ "$http_code" != "200" ]]; then
      echo "Login failed: $body" >&2
      return 1
    fi

    echo "Login successful" >&2
  fi
}

# Machine-to-machine API call (for cron/automation)
# Uses GANTT_MACHINE_TOKEN env var instead of cookie auth
api_call_machine() {
  local method="$1"
  local endpoint="$2"
  local data="${3:-}"

  local token="${GANTT_MACHINE_TOKEN:-}"
  if [[ -z "$token" ]]; then
    echo "Error: GANTT_MACHINE_TOKEN not set" >&2
    return 1
  fi

  local url="${API_URL}${endpoint}"
  local curl_opts=(-sS -w "\n%{http_code}" -X "$method" "$url" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer ${token}")

  if [[ -n "$data" ]]; then
    curl_opts+=(--data "$data")
  fi

  local response
  response=$(curl "${curl_opts[@]}") || return 1

  local http_code
  http_code=$(echo "$response" | tail -n1)
  local body
  body=$(echo "$response" | sed '$d')

  if [[ "$http_code" =~ ^2[0-9][0-9]$ ]]; then
    echo "$body"
    return 0
  fi

  echo "API request failed ($method $endpoint) HTTP $http_code" >&2
  echo "$body" | jq . 2>/dev/null >&2 || echo "$body" >&2
  return 1
}

api_call() {
  local method="$1"
  local endpoint="$2"
  local data="${3:-}"

  # Machine token path for automation/cron (no cookie auth needed)
  if [[ -n "${GANTT_MACHINE_TOKEN:-}" ]]; then
    api_call_machine "$method" "$endpoint" "$data"
    return $?
  fi

  ensure_cookie_store
  login_if_needed || return 1

  local url="${API_URL}${endpoint}"
  local curl_opts=(-sS -w "\n%{http_code}" -X "$method" "$url" -H "Content-Type: application/json" -b "$COOKIE_FILE" -c "$COOKIE_FILE")

  if [[ -n "$data" ]]; then
    curl_opts+=(--data "$data")
  fi

  local response
  response=$(curl "${curl_opts[@]}") || return 1

  local http_code
  http_code=$(echo "$response" | tail -n1)
  local body
  body=$(echo "$response" | sed '$d')

  if [[ "$http_code" =~ ^2[0-9][0-9]$ ]]; then
    echo "$body"
    return 0
  fi

  if [[ "$http_code" == "401" ]]; then
    echo "Unauthorized. Login first: ./gantt.sh auth login <email> <password>" >&2
  fi

  echo "API request failed ($method $endpoint) HTTP $http_code" >&2
  echo "$body" | jq . 2>/dev/null >&2 || echo "$body" >&2
  return 1
}
