<?php
namespace Bot\Services;

use Bot\Database;
use PDO;

class BalanceHoldService
{
    private PDO $pdo;
    private BalanceService $balances;

    public function __construct()
    {
        $this->pdo = Database::connection();
        $this->balances = new BalanceService();
    }

    public function createHold(int $userId, string $currency, string $amount, string $reason = null): int
    {
        $currency = strtoupper($currency);
        $this->balances->lock($userId, $currency, $amount);
        $stmt = $this->pdo->prepare(
            "INSERT INTO balance_holds (user_id, currency, amount, reason, status, created_at)
             VALUES (:user, :currency, :amount, :reason, 'active', NOW())"
        );
        $stmt->execute([
            ':user'     => $userId,
            ':currency' => $currency,
            ':amount'   => $amount,
            ':reason'   => $reason,
        ]);
        return (int) $this->pdo->lastInsertId();
    }

    public function releaseHold(int $holdId): bool
    {
        $stmt = $this->pdo->prepare('SELECT * FROM balance_holds WHERE id = ? AND status = \'active\'');
        $stmt->execute([$holdId]);
        $hold = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$hold) {
            return false;
        }
        $this->balances->unlock((int) $hold['user_id'], $hold['currency'], $hold['amount']);
        $update = $this->pdo->prepare(
            "UPDATE balance_holds SET status = 'released', released_at = NOW() WHERE id = ?"
        );
        $update->execute([$holdId]);
        return true;
    }

    /**
     * @return array<int,array<string,mixed>>
     */
    public function listHolds(int $userId): array
    {
        $stmt = $this->pdo->prepare(
            'SELECT id, currency, amount, reason, status, created_at, released_at
             FROM balance_holds
             WHERE user_id = ?
             ORDER BY id DESC'
        );
        $stmt->execute([$userId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
