<?php

namespace App\Modules\LodgingPlace\Domain;

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

class ListLodgingPlace implements StorageCriteria
{

    public function __construct(
        private string $action,
        private ?int $Id_Booking = null
    ) {}

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

    protected function query()
    {
        $select = LodgingPlace::select('`l`');
        $table = LodgingPlace::table();

        if ($this->action == 'all') {
            $where = '`l`.`LodgingPlace_Status` IN (1, 2)';
        } else if ($this->action == 'active') {
            $where = '`l`.`LodgingPlace_Status` = 2';
        } else if ($this->action == 'deleted') {
            $where = '`l`.`LodgingPlace_Status` = 0';
        } else {
            $where = '`l`.`LodgingPlace_Status` = 2';
        }

        if ($this->Id_Booking) {
            $where .= ' AND `l`.`Id_Booking` = ' . $this->Id_Booking;
        }
        return DB::select(
            "SELECT $select
            FROM $table l
            WHERE $where",
            []
        );
    }

    protected function analize($data)
    {
        return array_map(fn($dto) => LodgingPlace::fromDTO($dto), $data);
    }
}
