<?php

namespace Signteer\Core\Database;

use Plainwork\Database\Database;
use Plainwork\Database\Query;
use Signteer\Core\Criteria\EventLogCriteria;

class EventLogTable
{
    public const NAME = '__eventlog';
    public const COL_ID = 'id';
    public const COL_USER_ID = 'user_id';
    public const COL_EVENT_NAME = 'event_name';
    public const COL_EVENT_DATA = 'event_data';
    public const COL_WHEN = 'occured_at';

    public function up1($db)
    {
        $cols = [
            self::COL_ID => ['type' => 'INTEGER', 'null' => false, 'autoIncrement' => true, 'primaryKey' => true],
            self::COL_USER_ID => ['type' => 'INTEGER', 'null' => false],
            self::COL_EVENT_NAME => ['type' => 'VARCHAR(64)', 'null' => false],
            self::COL_EVENT_DATA => ['type' => 'TEXT', 'null' => false, 'default' => ''],
            self::COL_WHEN => ['type' => 'DATETIME', 'null' => false],
        ];
        $db->createTable(self::NAME, $cols);
    }

    public function down1($db)
    {
        $db->dropTable(self::NAME);
    }

    public function applyCriteria(Query $q, EventLogCriteria $c): Query
    {
        foreach ($c->getWhereId() as [$compare, $v]) {
            $q = $q->where(self::NAME . '.' . self::COL_ID, $compare, $v);
        }
        foreach ($c->getWhereUserId() as [$compare, $v]) {
            $q = $q->where(self::NAME . '.' . self::COL_USER_ID, $compare, $v);
        }

        return $q;
    }
}
