import { Injectable } from '@angular/core';
import { SectionConfig } from '../../shared/models/config';
import { SectionRenderNode } from './section-renderer.model';
import { WidgetRenderNode } from '../widget-host/widget-host.model';

@Injectable({ providedIn: 'root' })
export class SectionRendererService {
  toRenderNode(section: SectionConfig): SectionRenderNode {
    const widgets = (section.widgets ?? [])
      .filter(widget => widget.visible !== false)
      .sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
      .map<WidgetRenderNode>(widget => ({
        id: widget.id,
        type: widget.type,
        version: widget.version,
        order: widget.order,
        padding: widget.padding,
        visibility: widget.visibility,
        props: widget.props ?? {},
        featureFlag: widget.featureFlag,
        visible: widget.visible,
        source: widget
      }));

    return {
      id: section.id,
      type: section.type,
      order: section.order,
      layout: section.layout,
      visibility: section.visibility,
      featureFlag: section.featureFlag,
      visible: section.visible,
      widgets,
      source: section
    };
  }
}
