<?php

namespace App\Modules\CategoryProvider\Domain;

use App\Modules\Shared\Domain\QueryBuilder\Operator\OperatorBuilder;
use App\Modules\Shared\Domain\Storage\Criteria\ConcreteStorageCriteria;
use App\Modules\Shared\Domain\Storage\Criteria\SelectProjection;
use App\Modules\TypeProvider\Domain\IdTypeProvider;
use Illuminate\Support\Facades\DB;

class NextCategoryProviderLevel extends ConcreteStorageCriteria
{

    public function __construct(
        private IdTypeProvider $idTypeProvider,
        private bool $lockInShare = false
    ) {
        $op = new OperatorBuilder();

        $and = $op->and(
            $op->like('`Id_TypeProvider`', $idTypeProvider->value()),
            $op->in('`CategoryProvider_Status`', [1, 2])
        );

        parent::__construct(
            CategoryProvider::class,
            operator: $and,
            selects: [
                new SelectProjection('MAX(`CategoryProvider_Level`)', 'MaxLevel')
            ],
            lockInShare: $lockInShare
        );
    }

    public function analize($data)
    {
        if (empty($data)) {
            return new CategoryProviderLevel(1);
        }
        return new CategoryProviderLevel(($data[0]->MaxLevel ?? 0) + 1);
    }
}
