<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\Offers\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Maestro\Core\Modules\Offers\Enums\OfferSectionRole;
use Maestro\Core\Modules\Offers\Models\OfferSection;

/** @property OfferSection $resource */
final class OfferSectionResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $role = $this->section_role instanceof OfferSectionRole
            ? $this->section_role
            : OfferSectionRole::tryFrom((string) $this->section_role) ?? OfferSectionRole::Chapter;

        return [
            'id' => $this->id,
            'offer_id' => $this->offer_id,
            'parent_section_id' => $this->parent_section_id !== null ? (int) $this->parent_section_id : null,
            'section_role' => $role->value,
            'title' => $this->title,
            'description_html' => $this->description_html,
            'sort_order' => (int) $this->sort_order,
            'rows' => OfferRowResource::collection($this->whenLoaded('rows')),
            'children' => OfferSectionResource::collection($this->whenLoaded('children')),
        ];
    }
}
