<?php

namespace Mtc\Plugins\BlockManager\Services;

use Illuminate\Support\Str;
use Mtc\Plugins\BlockManager\Models\BlockManagerVariantDraft;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Round-trip helper — reads an on-disk published variant back into the Designer.
 *
 *   - Designer-authored (LESS has @designer-meta) → finds-or-creates a draft
 *     keyed by (element_type, variant_slug), returns { draft_id, read_only=false,
 *     properties_json }.
 *   - Foreign (no @designer-meta, e.g. Phase 2 starter or hand-authored) →
 *     returns { draft_id=null, read_only=true, properties_json=null }. The SPA
 *     surfaces a "Read-only — designed outside BlockManager" badge.
 *   - File missing → throws NotFoundHttpException so Laravel returns a clean 404.
 *
 * Idempotent by the natural key — repeated imports return the same draft id.
 */
class VariantImportService
{
    public function __construct(private VariantLessParser $parser)
    {
    }

    /**
     * @return array{
     *   element_type: string,
     *   variant_slug: string,
     *   twig_path: string,
     *   less_path: string,
     *   read_only: bool,
     *   draft_id: int|null,
     *   properties_json: array|null,
     * }
     */
    public function importExisting(string $elementType, string $variantSlug): array
    {
        $twigPath = base_path("plugins/BlockManager/elements/{$elementType}/variants/{$variantSlug}.twig");
        $lessPath = base_path("plugins/BlockManager/elements/{$elementType}/styles/{$variantSlug}.less");

        if (!is_file($twigPath) && !is_file($lessPath)) {
            throw new NotFoundHttpException("Variant {$elementType}/{$variantSlug} not found on disk.");
        }

        $envelope = [
            'element_type' => $elementType,
            'variant_slug' => $variantSlug,
            'twig_path'    => $twigPath,
            'less_path'    => $lessPath,
        ];

        $meta = null;
        if (is_file($lessPath)) {
            $meta = $this->parser->parse((string) file_get_contents($lessPath));
        }

        if ($meta === null) {
            return $envelope + [
                'read_only'       => true,
                'draft_id'        => null,
                'properties_json' => null,
            ];
        }

        $properties = is_array($meta['properties'] ?? null) ? $meta['properties'] : [];
        $draft = BlockManagerVariantDraft::where('element_type', $elementType)
            ->where('variant_slug', $variantSlug)
            ->first();

        if ($draft === null) {
            $draft = BlockManagerVariantDraft::create([
                'uuid'            => (string) Str::uuid(),
                'element_type'    => $elementType,
                'variant_slug'    => $variantSlug,
                'label'           => is_string($meta['label'] ?? null) ? $meta['label'] : null,
                'properties_json' => $properties,
            ]);
        }

        return $envelope + [
            'read_only'       => false,
            'draft_id'        => $draft->id,
            // Trust the persisted draft over the header if both exist — the
            // draft may carry unpublished edits.
            'properties_json' => $draft->properties_json ?? $properties,
        ];
    }
}
