<?php

namespace App\Modules\HtlCampBooking\Domain;

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

class IndexHtlCampBooking implements StorageCriteria
{

    public function __construct(
        private IdHtlCampBooking $id,
        private bool $lockInShare = false
    ) {
    }

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

    protected function query()
    {
        $select = HtlCampBooking::select('`hcb`');
        $lockInShare = $this->lockInShare ? 'LOCK IN SHARE MODE' : '';

        return DB::select(
            "SELECT $select,
                `hc`.`Id_HtlCamp`,
                `hc`.`HtlCamp_Name`,
                `hc`.`HtlCamp_Abrv`,
                `hc`.`HtlCamp_Availability`,
                `hc`.`HtlCamp_Status`,
                `hc`.`Id_HtlTypeCamp`
            FROM `t_htl_camp_booking` `hcb`
            INNER JOIN `t_htl_camp_schedule` `hcs` ON `hcb`.`Id_HtlCampSchedule` = `hcs`.`Id_HtlCampSchedule`
            INNER JOIN `t_htl_camp` `hc` ON `hcs`.`Id_HtlCamp` = `hc`.`Id_HtlCamp`
            WHERE `hcb`.`Id_HtlCampBooking` = ?
            $lockInShare",
            [
                $this->id->value()
            ]
        );
    }

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