<?php

namespace App\Addons\Base;

use Illuminate\Support\ServiceProvider;

/**
 * Base Addon Service Provider
 * All addon service providers should extend this class
 */
abstract class AddonServiceProvider extends ServiceProvider
{
    /**
     * Addon manifest data
     */
    protected array $manifest = [];

    /**
     * Register addon services
     */
    public function register(): void
    {
        // Override in addon
    }

    /**
     * Bootstrap addon services
     */
    public function boot(): void
    {
        // Load routes if they exist
        $this->loadRoutes();

        // Load views if they exist
        $this->loadViews();

        // Load migrations if they exist
        $this->loadMigrations();
    }

    /**
     * Load addon routes
     */
    protected function loadRoutes(): void
    {
        $slug = $this->getAddonSlug();
        $routesPath = base_path("addons/{$slug}/routes.php");

        if (file_exists($routesPath)) {
            $this->loadRoutesFrom($routesPath);
        }

        // Try web.php
        $webRoutesPath = base_path("addons/{$slug}/routes/web.php");
        if (file_exists($webRoutesPath)) {
            $this->loadRoutesFrom($webRoutesPath);
        }
    }

    /**
     * Load addon views
     */
    protected function loadViews(): void
    {
        $slug = $this->getAddonSlug();
        $viewsPath = base_path("addons/{$slug}/resources/views");

        if (is_dir($viewsPath)) {
            $this->loadViewsFrom($viewsPath, "addon.{$slug}");
        }
    }

    /**
     * Load addon migrations
     */
    protected function loadMigrations(): void
    {
        $slug = $this->getAddonSlug();
        $migrationsPath = base_path("addons/{$slug}/database/migrations");

        if (is_dir($migrationsPath)) {
            $this->loadMigrationsFrom($migrationsPath);
        }
    }

    /**
     * Get addon slug from class name or manifest
     */
    protected function getAddonSlug(): string
    {
        if (isset($this->manifest['slug'])) {
            return $this->manifest['slug'];
        }

        // Extract from class name (e.g., SampleAddonServiceProvider -> sample-addon)
        $className = class_basename($this);
        $slug = str_replace('ServiceProvider', '', $className);
        $slug = preg_replace('/([a-z])([A-Z])/', '$1-$2', $slug);

        return strtolower($slug);
    }

    /**
     * Set manifest data
     */
    public function setManifest(array $manifest): void
    {
        $this->manifest = $manifest;
    }
}
