<?php

namespace App\Modules\Cache\Domain;

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

class ListCache implements StorageCriteria
{

    public function __construct(
        private string $action
    ) {}

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

    protected function query()
    {
        $select = Cache::select('`l`');
        $table = Cache::table();
        if ($this->action == 'all') {
            $where = '`l`.`Cache_Status` IN (1, 2)';
        } else if ($this->action == 'active') {
            $where = '`l`.`Cache_Status` = 2';
        } else if ($this->action == 'deleted') {
            $where = '`l`.`Cache_Status` = 0';
        } else {
            $where = '`l`.`Cache_Status` = 2';
        }
        return DB::select(
            "SELECT $select
            FROM `$table` `l`
            WHERE $where
            ORDER BY `Cache_Order` ASC",
            []
        );
    }

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