<?php
namespace ProVM\Money\Common\Middleware;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as Handler;
use Psr\Http\Message\ResponseInterface as Response;
use Phinx\Wrapper\TextWrapper;
use GuzzleHttp\ClientInterface as Client;
use ProVM\Money\Common\Service\Update as Updater;

class Migrate {
  protected $phinx;
  protected $updater;
  public function __construct(TextWrapper $phinx, Updater $updater) {
    $this->phinx = $phinx;
    $this->updater = $updater;
  }

  public function __invoke(Request $request, Handler $handler): Response {
    $query = "SHOW TABLES";
    $st = \ORM::get_db()->query($query);
    $r = $st->fetchAll(\PDO::FETCH_ASSOC);
    if (count($r) == 0) {
      $this->phinx->getMigrate();
      $this->phinx->getSeed();
      $this->updater->update();
    }

    return $handler->handle($request);
  }
}
