<?php

namespace App\Modules\DefinedService\BriefingPassenger\Domain;

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

final class ListBriefingPassengerByGroup implements StorageCriteria
{
    public function __construct(private IdGroup $idGroup) {}

    public function run(): array
    {
        $rows = $this->query();
        return $this->analize($rows);
    }

    public function query(): array
    {
        $table = BriefingPassenger::table();

        $sql = "
            SELECT bp.*
            FROM `$table` AS bp
            WHERE bp.Id_Group = CAST(? AS UNSIGNED)
        ";

        return DB::select($sql, [(int)$this->idGroup->value()]);
    }

    private function analize(array $rows): array
    {
        if (!$rows) return [];

        return array_map(
            static fn($row) => BriefingPassenger::fromDTO($row),
            $rows
        );
    }
}
