<?php

namespace App\Http\Resources;

use App\Models\BulkImportLog;
use App\Models\ImportMap;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

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

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    #[\Override]
    public function toArray(Request $request): array
    {
        return $this->resource->map(fn (BulkImportLog $log) => [
            'when' => $log->created_at->format('d/m/Y H:i'),
            'who' => $log->author?->name ?? ($log->author_id ? 'Former user' : 'System'),
            'id' => $log->id,
            'type' => $this->getType($log),
            'data' => [
                'status' => isset($log->data['status']) ? __('labels.process-status.' . $log->data['status']) : '',
                'details' => $log->data['details'] ?? null,
            ],
            'automations' => $log->automations,
            'filename' => $log->filename,
            'file_link' => route('tenant.download-import-log-file', $log->id)
        ])->toArray();
    }

    private function getType(BulkImportLog $log): string
    {
        if (is_numeric($log->import_type)) {
            return ImportMap::query()->find($log->import_type)?->name;
        }
        return $log->import_type ?? 'Autonomy system default';
    }
}
