#!/usr/bin/env bash
# 本機 Go API（含內建 go job worker）
# 設定一律讀 deploy/.env.dev
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="$ROOT/deploy/.env.dev"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "找不到 $ENV_FILE，請先：cp deploy/.env.dev.example deploy/.env.dev" >&2
  exit 1
fi

set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a

: "${HAIXUN_API_PORT:=8890}"
: "${HAIXUN_MONGO_URI:?請在 deploy/.env.dev 設定 HAIXUN_MONGO_URI}"
: "${HAIXUN_MONGO_DB:=haixun}"
: "${HAIXUN_REDIS_ADDR:=127.0.0.1:6379}"
: "${HAIXUN_REDIS_PASSWORD:?請在 deploy/.env.dev 設定 HAIXUN_REDIS_PASSWORD}"
: "${HAIXUN_JWT_ACCESS_SECRET:?請在 deploy/.env.dev 設定 HAIXUN_JWT_ACCESS_SECRET}"
: "${HAIXUN_JWT_REFRESH_SECRET:?請在 deploy/.env.dev 設定 HAIXUN_JWT_REFRESH_SECRET}"
: "${HAIXUN_WORKER_SECRET:?請在 deploy/.env.dev 設定 HAIXUN_WORKER_SECRET}"

export HAIXUN_API_PORT HAIXUN_MONGO_URI HAIXUN_MONGO_DB
export HAIXUN_REDIS_ADDR HAIXUN_REDIS_PASSWORD
export HAIXUN_JWT_ACCESS_SECRET HAIXUN_JWT_REFRESH_SECRET
export HAIXUN_SECRETS_KEY="${HAIXUN_SECRETS_KEY:-}"
export HAIXUN_WORKER_SECRET
export THREADS_APP_ID="${THREADS_APP_ID:-}"
export THREADS_APP_SECRET="${THREADS_APP_SECRET:-}"
export THREADS_REDIRECT_URI="${THREADS_REDIRECT_URI:-https://threads-tool.30cm.net/api/v1/threads-accounts/oauth/callback}"
export THREADS_OAUTH_SUCCESS_REDIRECT="${THREADS_OAUTH_SUCCESS_REDIRECT:-https://threads-tool.30cm.net}"

cd "$ROOT/backend"
mkdir -p bin
go build -o bin/gateway gateway.go
exec ./bin/gateway -f etc/gateway.yaml