<?php

namespace App\Http\Resources;

use App\Events\LoadDealershipDataFields;
use App\ExportMaps\VehicleExportMap;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\App;

class ExportMapResource extends JsonResource
{
    public static $wrap = '';
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $this->resource->row_data = collect($this->resource->data['row_data'] ?? [])->keys();
        $this->resource->available_fields = collect($this->getFieldsForType())
                ->map(fn($value, $key) => [
                    'id' => $key,
                    'name' => "$value ($key) ",
                ])
                ->values();
        $resource = $this->resource->toArray();

        $resource['data_options'] = [
            'types' => collect(config('export_maps.types', []))
                ->map(fn ($type, $key) => [
                    'id' => $key,
                    'name' => App::make($type)->name(),
                ])->values(),
            'schedules' => collect(config('export_maps.schedule_types', []))
                ->map(fn ($type, $key) => [
                    'id' => $key,
                    'name' => __('export_maps.schedule_types.' . $key),
                ])->values(),
            'export_formats' => collect(config('export_maps.export_formats', []))
                ->map(fn ($type) => [
                    'id' => $type,
                    'name' => $type,
                ])->values(),
            'operators' => collect(config('export_maps.operators', []))
                ->map(fn ($type) => [
                    'id' => $type,
                    'name' => __('export_maps.operators.' . $type),
                ])->values(),
            'day_of_week' => collect(range(1, 7))
                ->map(fn ($day) => [
                    'id' => $day,
                    'name' => __('export_maps.day_of_week.' . $day),
                ])->values(),
            'day_of_month' => collect(range(1, 28))
                ->map(fn ($day) => [
                    'id' => $day,
                    'name' => $day,
                ])->values(),
            'export_drivers' => [
                [
                    'id' => 'sftp',
                    'name' => 'SFTP'
                ],
                [
                    'id' => 'ftp',
                    'name' => 'FTP'
                ],
            ]
        ];

        $resource['columns'] = $this->resource->columns ?? [];
        $resource['conditions'] = $this->resource->conditions ?? [];

        return $resource;
    }

    private function getFieldsForType(): array
    {
        return match ($this->resource->type) {
            'vehicle' => (new VehicleExportMap())->columns(),
            default => [],
        };
    }
}
