<?php

namespace App\Modules\DefinedService\BriefingPassenger\Domain;

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

class ListBriefingPassenger implements StorageCriteria
{
    public function __construct(
        private ?BriefingPassengerType $type,
        private string $action
    ) {}

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

    protected function query()
    {
        $select = BriefingPassenger::select('`bp`');
        $table = BriefingPassenger::table();
        $data = [];
        $where = '1=1';

        if ($this->type !== null) {
            $where .= ' AND `bp`.`BriefingPassenger_Type` = ?';
            $data[] = $this->type->value();
        }

        return DB::select(
            "SELECT $select
            FROM `$table` `bp`
            WHERE $where
            ORDER BY `BriefingPassenger_Date` DESC",
            $data
        );
    }

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