<?php

namespace App\Http\Resources;

use App\ExportMaps\Contracts\ExportMapType;
use App\IntegrationRepository;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\App;

class ExportMapTemplateResource extends JsonResource
{
    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    #[\Override]
    public function toArray(Request $request): array
    {
        $data = parent::toArray($request);

        return array_merge($data, [
            'data_options' => [
                'mapping_operators' => trans('export_map.operators'),
                'available_fields' => collect($this->getFieldsForType())
                    ->map(fn ($value, $key) => [
                        'id' => $key,
                        'name' => "$value ($key) ",
                    ])
                    ->sortBy('name')
                    ->values(),
                'sales_channels' => app(IntegrationRepository::class)
                    ->getAllForType('sales-channels')
                    ->keys()
            ]
        ]);
    }

    private function getFieldsForType(): array
    {
        $typeClass = config('export_maps.types.' . $this->resource->type);
        if (!$typeClass) {
            return [];
        }

        $instance = App::make($typeClass);
        return $instance instanceof ExportMapType ? $instance->columns(false) : [];
    }
}
