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

BASE_URL="${BASE_URL:-https://api.tooeasy.mixtech.dev.br}"
LOGIN_ENDPOINT="$BASE_URL/login"
EMAIL="${LOGIN_EMAIL:-admin@lumyon.tech}"
PASSWORD="${LOGIN_PASSWORD:-admin123}"

usage() {
    cat <<'USAGE'
Usage: LOGIN_EMAIL=<email> LOGIN_PASSWORD=<password> ./fetch_jwt.sh

Environment variables:
  BASE_URL       Base URL of the API (default: http://localhost:8000)
  LOGIN_EMAIL    Email used for authentication (default: tester@example.com)
  LOGIN_PASSWORD Password used for authentication (default: Password123!)
USAGE
}

if [[ -z "$EMAIL" || -z "$PASSWORD" ]]; then
    echo "[error] LOGIN_EMAIL and LOGIN_PASSWORD must be provided" >&2
    usage
    exit 1
fi

PAYLOAD=$(jq -n --arg email "$EMAIL" --arg password "$PASSWORD" '{email: $email, password: $password}')

RESPONSE=$(curl --fail --show-error --silent \
    -X POST "$LOGIN_ENDPOINT" \
    -H "Content-Type: application/json" \
    --data "$PAYLOAD")

TOKEN=$(echo "$RESPONSE" | jq -r '.data.token // empty')

if [[ -z "$TOKEN" ]]; then
    echo "[error] Unable to extract token from response" >&2
    echo "$RESPONSE" >&2
    exit 1
fi

echo "$TOKEN"
