<?php

namespace App\Modules\TourQuestion\Domain;

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

/**
 * @extends StorageCriteria<TourQuestion>
 */
class ListTourQuestion implements StorageCriteria
{

    public function __construct(
        private IdTour $idTour
    ) {
    }

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

    protected function query()
    {
        $select = RichTourQuestion::select('`tq`');
        return DB::select(
            "SELECT
                `tq`.`Id_TourQuestion`,
                `tq`.`TourQuestion_Order`,
                `tq`.`Id_Tour`,
                `tq`.`Id_Question`,

                `q`.`Question_Name`,
                `q`.`Id_TypeProvider`,
                `q`.`Question_Abrv`,
                ( IFNULL(
                        (
                            SELECT CONCAT(
                            '[',
                            GROUP_CONCAT(
                                JSON_OBJECT(
                                'Id_QuestionTypeProvider',            `qtp`.`Id_QuestionTypeProvider`,
                                'QuestionTypeProvider_Show',          `qtp`.`QuestionTypeProvider_Show`,
                                'QuestionTypeProvider_ForPassenger',  `qtp`.`QuestionTypeProvider_ForPassenger`,
                                'QuestionTypeProvider_Status',        `qtp`.`QuestionTypeProvider_Status`,
                                'Id_Question',                        `qtp`.`Id_Question`,
                                'Id_TypeProvider',                    `qtp`.`Id_TypeProvider`
                                )
                                SEPARATOR ','
                            ),
                            ']'
                            )
                            FROM      `t_question_type_provider` AS `qtp`
                            WHERE     `qtp`.`Id_Question` = `q`.`Id_Question`
                            AND       `qtp`.`QuestionTypeProvider_Status` = 2
                        ),
                        '[]'
                        ) ) AS `QuestionTypeProviderJSON`
                FROM    `t_tour_question`   AS `tq` INNER JOIN
                        `t_question`        AS `q`  ON `q`.`Id_Question` = `tq`.`Id_Question`
                WHERE   `Id_Tour` = ?
                ORDER BY `TourQuestion_Order` ASC;",
            [$this->idTour->value()]
        );
    }

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