<?php

declare(strict_types=1);

namespace App\Support\WorkspaceIsolation;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;

final class TenantOwnedRecordResolver
{
    public function resolve(Builder $query, Model|int|string|null $record): ?Model
    {
        $recordKey = $record instanceof Model ? $record->getKey() : $record;

        if ($recordKey === null || $recordKey === '') {
            return null;
        }

        return $query->whereKey($recordKey)->first();
    }

    public function resolveOrFail(Builder $query, Model|int|string|null $record): Model
    {
        $resolved = $this->resolve($query, $record);

        if ($resolved instanceof Model) {
            return $resolved;
        }

        throw (new ModelNotFoundException)->setModel($query->getModel()::class);
    }
}
