<?php

namespace App\Modules\WebContactMessage\Domain;

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

class FindByCodeWebContactMessage implements StorageCriteria
{

    private QueryBuilder $queryBuilder;

    public function __construct(
        private WebContactMessageCode $id,
        private bool $lockInShare = false
    ) {
        $this->queryBuilder = new QueryBuilder();
    }

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

    protected function query()
    {
        $queryBuilder = $this->queryBuilder->select(WebContactMessage::class, 'wcm')
            ->where('`wcm`.`WebContactMessage_Code`', '=', $this->id->value())
            ->where('`wcm`.`WebContactMessage_Status`', '<>', WebContactMessageStatus::DELETED);

        list($query, $values) = $queryBuilder->build();
        return DB::select(
            $query,
            $values
        );
    }

    protected function analize($data)
    {
        if (!count($data)) {
            throw new WebContactMessageNotExists();
        }
        return $this->queryBuilder->mainTable()->createFromDTO($data[0]);
    }
}
