<?php

namespace App\Modules\HtlCampSchedule\Domain;

use App\Modules\HtlCamp\Domain\IdHtlCamp;
use App\Modules\Shared\Domain\Storage\Criteria\StorageCriteria;
use Illuminate\Support\Facades\DB;

class AvailabilityHtlCampSchedule implements StorageCriteria
{

    public function __construct(
        private IdHtlCamp $idHtlCamp,
        private HtlCampScheduleDateSchedule $date,
        private bool $lockInShare = false
    ) {
    }

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

    protected function query()
    {
        $date = new HtlCampScheduleDateSchedule($this->date->value());
        $date->setTime(0, 0, 0);
        $select = HtlCampSchedule::select('`hcs`');
        $lockInShare = $this->lockInShare ? 'LOCK IN SHARE MODE' : '';

        return DB::select(
            "SELECT $select
            FROM `t_htl_camp_schedule` `hcs`
            WHERE `hcs`.`HtlCampSchedule_DateSchedule` = ?
            AND `hcs`.`Id_HtlCamp` = ?
            $lockInShare",
            [
                $this->date->value(),
                $this->idHtlCamp->value()
            ]
        );
    }

    protected function analize($data)
    {
        if (!count($data)) {
            return null;
        }
        return $data[0];
    }
}
