<?php

namespace App\Modules\LodgingPlace\Domain;

use App\Modules\Shared\Domain\Storage\Criteria\StorageCriteria;
use App\Modules\TypeProvider\Domain\IdTypeProvider;
use Illuminate\Support\Facades\DB;

class NextOrderLodgingPlace implements StorageCriteria
{

    public function __construct(
        private IdLodgingPlace $idLodgingPlace,
        private bool $lockInShare = false
    ) {}

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

    protected function query()
    {
        $select = LodgingPlace::select('`l`');
        $table = LodgingPlace::table();
        $query = "SELECT `l`.`LodgingPlace_Order`
            FROM `$table` `l`
            WHERE `l`.`Id_LodgingPlace` = ?
            AND `l`.`LodgingPlace_Status` <> 0
            ORDER BY `l`.`LodgingPlace_Order` DESC";
        if ($this->lockInShare) {
            $query .= ' LOCK IN SHARE MODE';
        }
        return DB::select($query, [$this->idLodgingPlace->value()]);
    }

    protected function analize($data)
    {
        if (empty($data)) {
            return new LodgingPlaceOrder(1);
        }
        return new LodgingPlaceOrder($data[0]['LodgingPlace_Order'] + 1);
    }
}
