<?php

namespace Src\Modules\Auth\Infrastructure\Queries;

use Src\Common\Infrastructure\TraitSqlQuery;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;
use Src\Modules\Auth\Interfaces\Infrastructure\Queries\IAdminsQuery;

class AdminsQuery implements IAdminsQuery {

    use TraitSqlQuery;

    private Builder $queryBuilder;

    private string $table;

    public function setTable(string $table): void
    {
        $this->table = $table;
    }

    public function select(array $fields = []): self
    {
        $allowFields = ['id', 'email', 'password_hash'];
        $select = $this->_getSelectSection($fields, $allowFields, $this->table);
        $this->queryBuilder = DB::table($this->table);
        $this->queryBuilder->select($select);
        return $this;
    }

    public function whereId(string $id): self
    {
        $this->queryBuilder->where($this->table . '.id', '=', $id);
        return $this;
    }
    
    public function whereIdIn(array $ids): self
    {
        $this->queryBuilder->whereIn($this->table . '.id', $ids);
        return $this;
    }

    public function whereEmail(string $email):self
    {
        $this->queryBuilder->where($this->table . '.email', '=', $email);
        return $this;
    }

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

    public function getCount(): int
    {
        return $this->queryBuilder->count();
    }

    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;
    }

    
}