<?php

namespace App\Filament\Pages;

use Illuminate\Database\Eloquent\Model;
use App\Api\Plugins\ApiPluginInterface;
use App\Models\ApiProvider;
use Illuminate\Support\Facades\File;
use Exception;
use ReflectionClass;

class Plugin extends Model
{
    protected $table = null; // No actual table

    protected $guarded = []; // Allow mass assignment for all attributes

    public $incrementing = false;

    protected $keyType = 'string';

    protected $primaryKey = 'id';

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        foreach ($attributes as $key => $value) {
            $this->$key = $value;
        }
    }

    public static function getAllPlugins()
    {
        $plugins = [];
        $path = app_path('Api/Plugins');

        if (File::exists($path)) {
            $files = File::files($path);
            foreach ($files as $file) {
                $filename = $file->getFilenameWithoutExtension();
                if (in_array($filename, ['ApiPluginInterface', 'LoggablePlugin', 'PluginLoader'])) {
                    continue;
                }
                $class = 'App\Api\Plugins\\' . $filename;

                if (class_exists($class) && in_array(ApiPluginInterface::class, class_implements($class))) {
                    try {
                        // Check if there's an ApiProvider for this plugin
                        $apiProvider = ApiProvider::where('plugin', $filename)->first();
                        $hasApiProvider = $apiProvider !== null;
                        
                        // Get plugin information without instantiating the class
                        // This avoids issues with plugins requiring ApiProvider in constructor
                        $reflection = new ReflectionClass($class);
                        $instance = $reflection->newInstanceWithoutConstructor();
                        
                        $plugins[] = new self([
                            'id' => $instance->getIdentifier(),
                            'name' => $instance->getName(),
                            'identifier' => $instance->getIdentifier(),
                            'enabled' => $hasApiProvider && $apiProvider->enabled,
                            'file_path' => $file->getPathname(),
                            'has_api_provider' => $hasApiProvider,
                            'configured' => $hasApiProvider
                        ]);
                    } catch (Exception $e) {
                        // Log error or handle as needed
                    }
                }
            }
        }
        return $plugins;
    }

    public function newCollection(array $models = [])
    {
        return new \Illuminate\Database\Eloquent\Collection($models);
    }
    
    public function newQuery()
    {
        // Create a new query builder instance
        $query = new \Illuminate\Database\Eloquent\Builder(
            new \Illuminate\Database\Query\Builder(
                \Illuminate\Support\Facades\DB::connection()->getQueryGrammar(),
                \Illuminate\Support\Facades\DB::connection()->getPostProcessor()
            )
        );
        
        // Set the model for the query builder
        $query->setModel($this);
        
        return $query;
    }
}