<?php
namespace App\Rules;

use App\Models\ProductFile;
use Illuminate\Contracts\Validation\ValidationRule;

class UniqueVersionNumber implements ValidationRule
{
    protected $productId;
    protected $isGlobal;
    protected $currentId;
    protected $conflictType;

    public function __construct($productId, $isGlobal, $currentId = null)
    {
        $this->productId = $productId;
        $this->isGlobal = $isGlobal;
        $this->currentId = $currentId;
        $this->conflictType = '';
    }

    public function validate(string $attribute, mixed $value, \Closure $fail): void
    {
        $exists = ProductFile::where('product_id', $this->productId)
            ->where('version', $value)
            ->where('is_global', $this->isGlobal)
            ->where('id', '!=', $this->currentId) // Exclude the current record
            ->exists();

        if ($exists) {
            $fail(
                $this->isGlobal
                    ? "The version number has already been defined at the global level for this product."
                    : "The version number has already been defined at the plan level for this product."
            );
        }
    }
}
