#!/usr/bin/env perl
use v5.38;
use FindBin;
use lib "$FindBin::Bin/../lib";
use Benchmark qw(cmpthese);
use DBIx::Fast;

# Mide el speedup real de cachear queries contra una SQLite local.
# Es el limite inferior del beneficio: en redes (MariaDB/Pg remotas)
# la latencia por query es 10-100x mayor, asi que el speedup escala.

my $db = DBIx::Fast->new(
    dsn        => 'dbi:SQLite:dbname=:memory:',
    driver     => 'SQLite',
    RaiseError => 1,
    PrintError => 0,
    cache      => { max_size => 10_000, default_ttl => 60 },
);

$db->exec(q{
    CREATE TABLE products (
        id    INTEGER PRIMARY KEY,
        sku   TEXT UNIQUE,
        name  TEXT,
        price REAL,
        stock INTEGER,
        descr TEXT
    )
});

# Catalogo de 1000 productos
$db->txn(sub {
    for my $i (1 .. 1000) {
        $db->insert('products', {
            sku   => "P$i",
            name  => "Product $i",
            price => 9.99 + ($i % 100),
            stock => $i % 50,
            descr => "Description for product number $i",
        });
    }
});

# Warm-up del cache para la version cached
my @ids = (1 .. 100);
$db->cached(ttl => 60, tag => 'products')
   ->hash('SELECT * FROM products WHERE id = ?', $_) for @ids;

say "=== hash() por ID (catalogo 1000 productos, SQLite in-memory) ===";
cmpthese(-3, {
    'no cache' => sub {
        $db->hash('SELECT * FROM products WHERE id = ?', $_) for @ids;
    },
    'cached'   => sub {
        $db->cached(ttl => 60, tag => 'products')
           ->hash('SELECT * FROM products WHERE id = ?', $_) for @ids;
    },
});

say "\n=== all() catalogo completo (1000 filas) ===";
cmpthese(-3, {
    'no cache' => sub {
        $db->all('SELECT * FROM products WHERE stock > 0 ORDER BY id LIMIT 100');
    },
    'cached'   => sub {
        $db->cached(ttl => 60, tag => 'products')
           ->all('SELECT * FROM products WHERE stock > 0 ORDER BY id LIMIT 100');
    },
});

say "\n=== val() agregacion ===";
cmpthese(-3, {
    'no cache' => sub {
        $db->val('SELECT COUNT(*) FROM products WHERE price > 50');
    },
    'cached'   => sub {
        $db->cached(ttl => 60, tag => 'products')
           ->val('SELECT COUNT(*) FROM products WHERE price > 50');
    },
});

say "\n=== Stats cache acumulado ===";
my $s = $db->cache->stats;
printf "  hits:        %d\n",   $s->{hits};
printf "  misses:      %d\n",   $s->{misses};
printf "  hit_ratio:   %.2f%%\n", $s->{hit_ratio} * 100;
printf "  invalidations: %d\n",  $s->{invalidations};
