<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\DB;

class UniqueActiveSlug implements ValidationRule
{
    public function __construct(
        private readonly string $table,
        private readonly ?string $franchiseeId = null,
        private readonly ?string $ignoreId = null,
        private readonly string $slugColumn = 'slug',
        private readonly string $scopeColumn = 'franchisee_id',
    ) {
    }

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if ($value === null || $value === '') {
            return;
        }

        $query = DB::table($this->table)
            ->where($this->slugColumn, $value)
            ->whereNull('deleted_at');

        if ($this->franchiseeId === null) {
            $query->whereNull($this->scopeColumn);
        } else {
            $query->where($this->scopeColumn, $this->franchiseeId);
        }

        if ($this->ignoreId) {
            $query->where('id', '!=', $this->ignoreId);
        }

        if ($query->exists()) {
            $fail('The slug has already been taken.');
        }
    }
}
