<?php
// STORAGE/WATCHING — отложенный вход по просадке
require_once __DIR__ . '/db.php';

// ---------------------------------------------------------------
// Watching (watching)
// ---------------------------------------------------------------

/**
 * Загружает watching-записи entity.
 * Возвращает ['SYMBOL' => [...поля...]] — тот же формат что файловый вариант.
 */
function storage_load_watching(string $entityType, string $entityId): array
{
    $db   = storage_db();
    $stmt = $db->prepare('SELECT * FROM watching WHERE entity_type = ? AND entity_id = ?');
    $stmt->execute([$entityType, $entityId]);
    $rows = $stmt->fetchAll();

    $result = [];
    foreach ($rows as $row) {
        $entry = [
            'side'               => $row['side'],
            'trader_entry_price' => (float)  $row['trader_entry_price'],
            'trade_id'           => $row['trade_id'],
            'leverage'           => (int)    $row['leverage'],
            'source'             => $row['source'],
            'trader_size_usd'    => isset($row['trader_size_usd']) ? (float) $row['trader_size_usd'] : null,
            'symbol_exchange'    => $row['symbol_exchange'] ?? null,
            'started_at'         => (int)    $row['started_at'],
        ];

        if ($row['source'] === 'wallet') {
            $entry['wallet_id'] = $entityId;
        } else {
            $entry['pool_id']      = $row['pool_id'];
            $entry['trader_id']    = $row['trader_id'];
            $entry['trader_label'] = $row['trader_label'];
        }

        $result[$row['symbol']] = $entry;
    }

    return $result;
}

/**
 * Добавляет запись в watching (INSERT OR IGNORE — не перезаписывает существующую).
 */
function storage_add_watching(string $entityType, string $entityId, string $symbol, array $entry): bool
{
    $db   = storage_db();
    $stmt = $db->prepare('
        INSERT OR IGNORE INTO watching
            (entity_type, entity_id, symbol, side, trader_entry_price, trade_id,
             leverage, source, pool_id, trader_id, trader_label, trader_size_usd,
             symbol_exchange, started_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ');
    $stmt->execute([
        $entityType, $entityId, $symbol,
        $entry['side'],
        (float)  ($entry['trader_entry_price'] ?? 0),
        $entry['trade_id']    ?? '',
        (int)    ($entry['leverage']           ?? 1),
        $entry['source']      ?? 'wallet',
        $entry['pool_id']     ?? null,
        $entry['trader_id']   ?? null,
        $entry['trader_label'] ?? null,
        isset($entry['trader_size_usd']) ? (float) $entry['trader_size_usd'] : null,
        $entry['symbol_exchange'] ?? null,
        $entry['started_at']  ?? time(),
    ]);

    return $stmt->rowCount() > 0;
}

/**
 * Удаляет конкретный символ из watching.
 */
function storage_remove_watching(string $entityType, string $entityId, string $symbol): void
{
    $db = storage_db();
    $db->prepare('DELETE FROM watching WHERE entity_type = ? AND entity_id = ? AND symbol = ?')
       ->execute([$entityType, $entityId, $symbol]);
}

/**
 * Сохраняет watching полностью (DELETE + INSERT) — для совместимости с save_watching().
 */
function storage_save_watching(string $entityType, string $entityId, array $watching): void
{
    $db = storage_db();
    storage_retry(function() use ($db, $entityType, $entityId, $watching) {
    $db->beginTransaction();
    try {
        $db->prepare('DELETE FROM watching WHERE entity_type = ? AND entity_id = ?')
           ->execute([$entityType, $entityId]);

        if (!empty($watching)) {
            $stmt = $db->prepare('
                INSERT INTO watching
                    (entity_type, entity_id, symbol, side, trader_entry_price, trade_id,
                     leverage, source, pool_id, trader_id, trader_label, trader_size_usd,
                     symbol_exchange, started_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ');
            foreach ($watching as $symbol => $entry) {
                $stmt->execute([
                    $entityType, $entityId, $symbol,
                    $entry['side'],
                    (float)  ($entry['trader_entry_price'] ?? 0),
                    $entry['trade_id']     ?? '',
                    (int)    ($entry['leverage']           ?? 1),
                    $entry['source']       ?? 'wallet',
                    $entry['pool_id']      ?? null,
                    $entry['trader_id']    ?? null,
                    $entry['trader_label'] ?? null,
                    isset($entry['trader_size_usd']) ? (float) $entry['trader_size_usd'] : null,
                    $entry['symbol_exchange'] ?? null,
                    (int)    ($entry['started_at']         ?? time()),
                ]);
            }
        }

        $db->commit();
    } catch (Throwable $e) {
        $db->rollBack();
        throw $e;
    }
    }); // storage_retry
}
