#!/bin/bash
# Sync product catalogs from POD providers
#
# Fetches the latest product catalog from Printful and Prodigi
# and caches locally for offline reference.
#
# Usage: ./scripts/sync-catalog.sh [provider]
# Example: ./scripts/sync-catalog.sh printful

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
CACHE_DIR="$PROJECT_DIR/.cache/catalogs"

PROVIDER=${1:-all}

mkdir -p "$CACHE_DIR"

echo "🍄 Syncing POD Catalogs"
echo "======================="
echo ""

sync_printful() {
    echo "Syncing Printful catalog..."

    if [ -z "$PRINTFUL_API_TOKEN" ]; then
        echo "  ⚠ PRINTFUL_API_TOKEN not set, skipping"
        return
    fi

    curl -s -H "Authorization: Bearer $PRINTFUL_API_TOKEN" \
        "https://api.printful.com/products" \
        > "$CACHE_DIR/printful-catalog.json"

    count=$(jq '.result | length' "$CACHE_DIR/printful-catalog.json" 2>/dev/null || echo "0")
    echo "  ✓ Saved $count products to printful-catalog.json"
}

sync_prodigi() {
    echo "Syncing Prodigi catalog..."

    API_KEY="${PRODIGI_API_KEY_SANDBOX:-$PRODIGI_API_KEY_LIVE}"
    if [ -z "$API_KEY" ]; then
        echo "  ⚠ PRODIGI_API_KEY not set, skipping"
        return
    fi

    curl -s -H "X-API-Key: $API_KEY" \
        "https://api.sandbox.prodigi.com/v4.0/products" \
        > "$CACHE_DIR/prodigi-catalog.json"

    count=$(jq '.products | length' "$CACHE_DIR/prodigi-catalog.json" 2>/dev/null || echo "0")
    echo "  ✓ Saved $count products to prodigi-catalog.json"
}

# Load environment
if [ -f "$PROJECT_DIR/config/.env" ]; then
    export $(cat "$PROJECT_DIR/config/.env" | grep -v '^#' | xargs)
fi

case $PROVIDER in
    printful)
        sync_printful
        ;;
    prodigi)
        sync_prodigi
        ;;
    all)
        sync_printful
        sync_prodigi
        ;;
    *)
        echo "Unknown provider: $PROVIDER"
        echo "Usage: $0 [printful|prodigi|all]"
        exit 1
        ;;
esac

echo ""
echo "Catalogs cached in: $CACHE_DIR"
echo ""
echo "View catalogs with:"
echo "  jq '.result[] | {id, title}' $CACHE_DIR/printful-catalog.json"
echo "  jq '.products[] | {sku, description}' $CACHE_DIR/prodigi-catalog.json"
