<?php

namespace App\Http\Resources;

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

/**
 * Builds the Sales Channels list from two sources:
 *  - the enabled built-in integrations (keyed by channel slug), and
 *  - the export maps assigned to a channel.
 *
 * Rules applied here:
 *  - Only export maps with "Automated export to FTP server" enabled are a feed.
 *  - An active export map supersedes (hides) its built-in integration tile.
 *
 * Expects the resource to be: [
 *   'integrations' => Collection<string, array>  // getAllForType('sales-channels', true)
 *                                                 // all channels, each with an 'active' flag
 *   'export_maps'  => Collection<int, array>      // ExportMapRepository::salesChannelMaps()
 * ]
 *
 * The full (all-channel) integration list doubles as the icon source for export
 * map entries, whose channel may itself be disabled or hidden.
 */
class SalesChannelList extends JsonResource
{
    public static $wrap = '';

    #[\Override]
    public function toArray(Request $request): array
    {
        $exportMaps = $this->feedExportMaps();
        $channelsWithActiveExportMap = $exportMaps
            ->filter(fn (array $map) => $map['active'])
            ->pluck('sales_channel')
            ->unique();

        return [
            'data' => $this->integrationItems($channelsWithActiveExportMap)
                ->concat($this->exportMapItems($exportMaps))
                ->values()
                ->toArray(),
            'default_columns' => ['last-synced'],
        ];
    }

    /**
     * Export maps that actually feed a channel (auto FTP export enabled).
     */
    private function feedExportMaps(): Collection
    {
        return collect($this->resource['export_maps'])
            ->filter(fn (array $map) => $map['ftp_export_enabled'])
            ->values();
    }

    private function integrationItems(Collection $channelsWithActiveExportMap): Collection
    {
        return collect($this->resource['integrations'])
            ->filter(fn (array $integration) => (bool) ($integration['active'] ?? false))
            ->reject(fn ($integration, $key) => $channelsWithActiveExportMap->contains($key))
            ->map(function (array $channel, string $key) {
                $name = App::make($channel['class'])->name();

                return [
                    'title' => $name,
                    'image' => $this->image($channel['image']['src'] ?? null, $name),
                    'metaItems' => ['last-synced' => $this->lastSynced($key)],
                    'link' => '/manage-content/sales-channels/edit/' . $key,
                ];
            })
            ->values();
    }

    private function exportMapItems(Collection $exportMaps): Collection
    {
        $icons = collect($this->resource['integrations']);

        return $exportMaps
            ->map(fn (array $map) => [
                'title' => $map['name'],
                'image' => $this->image($icons->get($map['sales_channel'])['image']['src'] ?? null, $map['sales_channel']),
                'active' => $map['active'],
                'status' => $map['active']
                    ? __('sales_channels.export_map_active')
                    : __('sales_channels.export_map_inactive'),
                'metaItems' => ['last-synced' => $map['last_sent_at'] ?? __('sales_channels.not_synced')],
                'link' => '/settings/export-maps/edit/' . $map['id'],
            ])
            ->values();
    }

    private function image(?string $asset, string $alt): array
    {
        return [
            'src' => $asset ? config('app.url') . '/api/assets/' . $asset : null,
            'alt' => $alt,
        ];
    }

    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',
        ]);
    }
}
