<?php

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

if (!function_exists('package_path')) {
    function package_path($path = ''): string
    {
        return __DIR__ . '/../../' . ltrim($path, '/');
    }
}

if (!function_exists('resolveModelClass')) {
    function resolveModelClass(string $name, string $identifierVal, string $identifierName = 'id')
    {
        // Generate the fully qualified model class name dynamically
        $modelClassName = 'Artemis\\Faq\\Models\\' . ucfirst(strtolower(trim($name)));

        // Ensure the class exists and is an instance of Model
        if (!class_exists($modelClassName)) {
            throw new ModelNotFoundException("Model class '{$modelClassName}' does not exist.");
        }

        if (!is_subclass_of($modelClassName, Model::class)) {
            throw new ModelNotFoundException("Class '{$modelClassName}' is not a valid Eloquent model.");
        }

        $model = new $modelClassName();

        // Use Eloquent to find the model by the given identifier
        return $model->where($identifierName, $identifierVal)->firstOrFail();
    }
}

if (!function_exists('generateSlugForModel')) {
    function generateSlugForModel(string $title, Model|string $model, string $slugColumn = 'slug'): string
    {
        if (empty($title)) {
            throw new InvalidArgumentException("Title cannot be empty.");
        }

        if (is_string($model)) {
            if (!class_exists($model)) {
                throw new ModelNotFoundException("Model class '{$model}' does not exist.");
            }
            $model = new $model();
        }

        $baseSlug = Str::slug($title);
        $slug = $baseSlug;

        $suffix = 1;
        while ($model::where($slugColumn, $slug)->exists()) {
            $slug = "$baseSlug-$suffix";
            $suffix++;
        }

        return $slug;
    }
}

if (!function_exists('getTablePrefix')) {
    function getTablePrefix(): string
    {
        return trim(config('artemis.table_prefix'), '_') . '_';
    }
}

if (!function_exists('prefixedTable')) {
    function prefixedTable(string $table): string
    {
        $prefix = getTablePrefix();

        // if $table already begins with “faq_”, just return it
        if (str_starts_with($table, $prefix)) {
            return $table;
        }

        return $prefix . $table;
    }
}
