<?php

namespace App\Modules\WebContactMessage\Domain;

use App\Modules\Leads\WebChannel\Domain\WebChannel;
use App\Modules\Leads\WebPage\Domain\WebPage;
use App\Modules\Shared\Domain\DateTimeEnd;
use App\Modules\Shared\Domain\DateTimeStart;
use App\Modules\Shared\Domain\QueryBuilder\Operator\OperatorAllIn;
use App\Modules\Shared\Domain\QueryBuilder\Operator\OperatorAnd;
use App\Modules\Shared\Domain\QueryBuilder\Operator\OperatorBetween;
use App\Modules\Shared\Domain\QueryBuilder\Operator\OperatorNotEqual;
use App\Modules\Shared\Domain\QueryBuilder\QueryBuilder;
use App\Modules\Shared\Domain\Storage\Criteria\StorageCriteria;
use App\Modules\WebContact\Domain\WebContactModel;
use App\Modules\WebContactMessageDetail\Domain\WebContactMessageDetailModel;
use Illuminate\Support\Facades\DB;

class ExistsWebContactMessage implements StorageCriteria
{

    private QueryBuilder $queryBuilder;

    public function __construct(
        private IdWebContactMessage $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`.`Id_WebContactMessage`', '=', $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]);
    }
}
