<?php

namespace App\Modules\PaxInformationRoom\Domain;

use App\Modules\PaxInformation\Domain\PaxInformation;
use App\Modules\PaxInformationRoom\Application\Index\IndexPaxInformationRoomPopulate;
use App\Modules\Shared\Domain\QueryBuilder\QueryBuilder;
use App\Modules\Shared\Domain\Storage\Criteria\StorageCriteria;
use App\Modules\TypeRoom\Domain\TypeRoom;
use Illuminate\Support\Facades\DB;

class IndexPaxInformationRoom implements StorageCriteria
{

    private QueryBuilder $queryBuilder;

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

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

    protected function query()
    {
        $populateStrings = [
            IndexPaxInformationRoomPopulate::PAX_INFORMATION => [PaxInformation::class, 'Id_PaxInformation', 'ls', 'INNER', 'setPaxInformation'],
            IndexPaxInformationRoomPopulate::TYPE_ROOM => [TypeRoom::class, 'Id_TypeRoom', 'le', 'INNER', 'setTypeRoom'],
        ];
        $queryBuilder = $this->queryBuilder->select(PaxInformationRoom::class, 'r')
            ->where('`r`.`Id_PaxInformationRoom`', '=', $this->id->value())
            ->where('`r`.`PaxInformationRoom_Status`', '<>', PaxInformationRoomStatus::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 PaxInformationRoomNotFound();
        }
        $tour = $this->queryBuilder->mainTable()->createFromDTO($data[0]);
        foreach ($this->queryBuilder->populates() as $populate) {
            $tour->{$populate['setter']}($populate['table']->createFromDTO($data[0]));
        }
        return $tour;
    }
}
