#!/bin/bash
# Upload Cian session cookies to backend for Valuation Calculator auth.
#
# Usage: ./scripts/upload-cian-cookies.sh [cookies.json]
#
# cookies.json — JSON object { cookie_name: cookie_value, ... }
# Экспортируется из Chrome DevTools → Application → Cookies → www.cian.ru
# или через расширение Cookie-Editor → Export → JSON (object format).
#
# Переменные окружения:
#   TRADEIN_BASE_URL     — base URL (default: https://gendsgn.ru/trade-in)
# Auth: Caddy basic_auth (auth handled by curl --user / browser session).

set -euo pipefail

COOKIES_FILE="${1:-cookies.json}"

if [[ ! -f "$COOKIES_FILE" ]]; then
  echo "Error: cookies file not found: $COOKIES_FILE" >&2
  echo "Usage: $0 cookies.json" >&2
  exit 1
fi

BASE_URL="${TRADEIN_BASE_URL:-https://gendsgn.ru/trade-in}"

echo "Uploading Cian cookies from $COOKIES_FILE to $BASE_URL ..."
echo

curl -fsSL -X POST "$BASE_URL/api/v1/admin/scrape/cian/upload-cookies" \
  -H "Content-Type: application/json" \
  -d "@$COOKIES_FILE" \
  | python3 -m json.tool

echo
echo "Verifying session:"
curl -fsSL "$BASE_URL/api/v1/admin/scrape/cian/test-auth" \
  | python3 -m json.tool
