<?php

namespace App\Modules\History\Domain;

use App\Modules\HistoryTable\Domain\IdHistoryTable;
use App\Modules\Shared\Domain\DateEnd;
use App\Modules\Shared\Domain\DateStart;
use App\Modules\Shared\Domain\QueryList\QueryPaginate;
use App\Modules\Shared\Domain\Storage\Criteria\StorageCriteria;
use Illuminate\Support\Facades\DB;

class ListHistory implements StorageCriteria
{

    public function __construct(
        private DateStart $dateStart,
        private DateEnd $dateEnd,
        private IdHistoryTable $idHistoryTable,
        private IdHistoryReference $idHistoryReference,
        private QueryPaginate $queryPaginate,
        private string $action
    ) {
    }

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

    protected function query()
    {
        $select = History::select('`h`');

        $where = '`h`.`Id_HistoryTable` = ?';
        $data = [$this->idHistoryTable->value()];

        if (!($this->idHistoryReference->value() === 0 || $this->idHistoryReference->value() === null)) {
            $where = ' AND `h`.`Id_Reference` = ?';
            $data[] = $this->idHistoryReference->value();
        }

        $where .= ' AND `h`.`History_Date` BETWEEN ? AND ?';
        $data[] = $this->dateStart->value() . ' 00:00:00';
        $data[] = $this->dateEnd->value() . ' 23:59:59';

        if ($this->queryPaginate->isPaginated()) {
            $limit = "LIMIT " . $this->queryPaginate->getOffset() . ", " . $this->queryPaginate->getLimit();
        }
        return DB::select(
            "SELECT $select,

                `a`.`Id_Admin`,
                `a`.`Admin_Name`,
                `a`.`Admin_LastName`,
                `a`.`Admin_NoDocument`,

                `ht`.`Id_HistoryTable`,
                `ht`.`HistoryTable_Name`,
                `ht`.`HistoryTable_Title`
            FROM `t_history` `h`
            INNER JOIN `t_history_table` `ht` ON `ht`.`Id_HistoryTable` = `h`.`Id_HistoryTable`
            LEFT JOIN `t_admin` `a` ON `a`.`Id_Admin` = `h`.`Id_Admin`
            WHERE $where
            ORDER BY `h`.`Id_History` DESC
            $limit",
            $data
        );
    }

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