<?php

namespace App\Modules\Room\Domain;

use App\Modules\DefinedService\Location\Domain\Location;
use App\Modules\Room\Application\Index\IndexRoomPopulate;
use App\Modules\DefinedService\TypeDefinedService\Domain\TypeDefinedService;
use App\Modules\Shared\Domain\QueryBuilder\QueryBuilder;
use App\Modules\Shared\Domain\Storage\Criteria\StorageCriteria;
use Illuminate\Support\Facades\DB;

class IndexRoom implements StorageCriteria
{

    private QueryBuilder $queryBuilder;

    public function __construct(
        private IdRoom $id,
        private IndexRoomPopulate $populate,
        private bool $lockInShare = false
    ) {
        $this->queryBuilder = new QueryBuilder();
    }

    public function run()
    {
        return $this->analize($this->query());
    }

    protected function query()
    {
        $populateStrings = [];
        $queryBuilder = $this->queryBuilder->select(Room::class, 'r')
            ->where('`r`.`Id_Room`', '=', $this->id->value())
            ->where('`r`.`Room_Status`', '<>', RoomStatus::DELETED);

        foreach ($this->populate->getValue() as $populate) {
            if (array_key_exists($populate, $populateStrings)) {
                $queryBuilder->populate(...$populateStrings[$populate]);
            }
        }

        list($query, $values) = $queryBuilder->build();
        return DB::select(
            $query,
            $values
        );
    }

    protected function analize($data)
    {
        if (!count($data)) {
            throw new RoomNotFound();
        }
        $tour = $this->queryBuilder->mainTable()->createFromDTO($data[0]);
        foreach ($this->queryBuilder->populates() as $populate) {
            $tour->{$populate['setter']}($populate['table']->createFromDTO($data[0]));
        }
        return $tour;
    }
}
