<?php

namespace App\Extensions;

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class ManifestValidator
{
    /**
     * Validate an extension manifest
     *
     * @param array $manifest
     * @return bool
     * @throws ValidationException
     */
    public static function validate(array $manifest): bool
    {
        $validator = Validator::make($manifest, [
            'id' => ['required', 'string', 'alpha_dash', 'max:50'],
            'name' => ['required', 'string', 'max:100'],
            'description' => ['required', 'string', 'max:500'],
            'version' => ['required', 'string', 'regex:/^\d+\.\d+\.\d+$/'],
            'author' => ['required', 'string', 'max:100'],
            'homepage' => ['nullable', 'url'],
            'icon' => ['nullable', 'string'],
            'requires' => ['nullable', 'array'],
            'requires.ticaga' => ['nullable', 'string', 'regex:/^\d+\.\d+\.\d+$/'],
            'requires.php' => ['nullable', 'string'],
            'requires.laravel' => ['nullable', 'string'],
            'capabilities' => ['nullable', 'array'],
            'capabilities.*' => ['string'],
            'config' => ['nullable', 'array'],
        ]);

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }

        return true;
    }

    /**
     * Get required manifest fields
     */
    public static function getRequiredFields(): array
    {
        return [
            'id',
            'name',
            'description',
            'version',
            'author',
        ];
    }

    /**
     * Get optional manifest fields
     */
    public static function getOptionalFields(): array
    {
        return [
            'homepage',
            'icon',
            'requires',
            'capabilities',
            'config',
        ];
    }

    /**
     * Generate a sample manifest structure
     */
    public static function getSampleManifest(): array
    {
        return [
            'id' => 'my-extension',
            'name' => 'My Extension',
            'description' => 'A brief description of what this extension does',
            'version' => '1.0.0',
            'author' => 'Your Name',
            'homepage' => 'https://example.com',
            'icon' => 'heroicon-o-puzzle-piece',
            'requires' => [
                'ticaga' => '2.2.0',
                'php' => '8.2',
                'laravel' => '12.0',
            ],
            'capabilities' => [
                'import',
                'export',
            ],
            'config' => [
                'setting_key' => 'default_value',
            ],
        ];
    }
}
