<?php

namespace App\Http\Resources;

use App\Enums\ExportColumnJsonType;
use App\ExportMaps\Contracts\ExportMapType;
use App\Exports\JsonMapExport;
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(),
                'export_formats' => collect(config('export_maps.export_formats', []))
                    ->map(fn ($type) => [
                        'id' => $type,
                        'name' => $type,
                    ])->values(),
                'column_json_types' => collect(ExportColumnJsonType::cases())
                    ->map(fn ($case) => [
                        'id' => $case->value,
                        'name' => $case->value,
                    ])
                    ->values(),
                'json_envelope_tokens' => JsonMapExport::envelopeTokenCatalogue(),
            ]
        ]);
    }

    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) : [];
    }
}
