<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\SalesChannelHistory;

class SalesChannelList extends JsonResource
{
    public static $wrap = '';
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    #[\Override]
    public function toArray(Request $request): array
    {
        return [
            'data' => $this->resource->map(fn ($channel, $key) => [
                'title' => App::make($channel['class'])->name(),
                'image' => [
                    'src' => config('app.url') . '/api/assets/' . $channel['image']['src'],
                    'alt' => App::make($channel['class'])->name(),
                ],
                'metaItems' => [
                    'last-synced' => $this->lastSynced($key),
                ],
                'link' => '/manage-content/sales-channels/edit/' . $key,
            ])->values()->toArray(),
            'default_columns' => [
                'last-synced',
            ]
        ];
    }

    private function lastSynced(string $channel)
    {
        $lastSync = SalesChannelHistory::query()->where('channel', $channel)->latest()->first();
        if (!$lastSync) {
            return __('sales_channels.not_synced');
        }
        return __('sales_channels.last_sync_time', [
            'time' => $lastSync->updated_at,
            'status' => $lastSync->was_successful ? 'OK' : 'Failed',
        ]);
    }
}
