<?php

namespace Src\Modules\JsonObjects\Infrastructure;

use Src\Modules\JsonObjects\Interfaces\Infrastructure\IItemQuery;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;
use Src\Common\Infrastructure\TraitSqlQuery;

class ItemQuery implements IItemQuery
{

    use TraitSqlQuery {
        TraitSqlQuery::getSelectSection as baseGetSelectSection;
    }

    protected string $tableName;

    protected Builder $queryBuilder;

    public function setTableName(string $tableName)
    {
        $this->tableName = $tableName;
    }

    public function select(array $fields = [])
    {
        $this->queryBuilder = DB::table($this->tableName);
        $select = $this->_getSelectSection($fields, ['id', 'dir_id', 'key', 'name', 'description', 'object', 'disabled'], $this->tableName);
        $this->queryBuilder->select($select);
        return $this;
    }

    public function whereId(string $id)
    {
        $this->queryBuilder->where($this->tableName . '.id', '=', $id);
        return $this;
    }

    public function whereIdIn(array $ids)
    {
        $this->queryBuilder->whereIn($this->tableName . '.id', $ids);
        return $this;
    }

    public function whereType(string $type)
    {
        // $this->queryBuilder->whereJsonContains('object->type', $type);
        $this->queryBuilder->whereJsonContains($this->tableName . '.object', ['type' => $type]);
        return $this;
    }

    public function getByKey(string $key)
    {
        $this->queryBuilder->where($this->tableName . '.key', '=', $key);
        return $this;
    }

    public function whereKey(string $key)
    {
        $this->queryBuilder->where($this->tableName . '.key', '=', $key);
        return $this;
    }

    public function whereDirId(string $dirId)
    {
        $this->queryBuilder->where($this->tableName . '.dir_id', '=', $dirId);
        return $this;
    }

    public function limit(int $limit, int $offset)
    {
        $this->queryBuilder->limit($limit)->offset($offset);
        return $this;
    }

    public function all(): array
    {
        $result = [];
        foreach ($this->queryBuilder->get()->all() as $row) {
            $result[$row->id] = $row;
        }
        return json_decode(json_encode($result), true);
    }

    public function one(): array
    {
        $result = $this->queryBuilder->first() ?? [];
        $result = json_decode(json_encode($result), true);
        return $result;
    }
}
