<?php

namespace App\Modules\PaxInformationRoomPassenger\Domain;

use App\Modules\PaxInformation\Domain\PaxInformation;
use App\Modules\PaxInformationRoomPassenger\Application\Index\IndexPaxInformationRoomPassengerPopulate;
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 IndexPaxInformationRoomPassenger implements StorageCriteria
{

    private QueryBuilder $queryBuilder;

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

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

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