<?php

namespace App;

use App\Contracts\SmartImageManagementDriver;
use Illuminate\Support\Facades\App;
use Mtc\ContentManager\Contracts\MediaUse;
use Mtc\ContentManager\Http\Resources\MediaEntryResource;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleOffer;

class SmartImageManagementRepository
{
    protected SmartImageManagementDriver $driver;
    protected array $data;

    public function hasEnabledIntegration(): bool
    {
        return $this->getEnabledIntegrations()->isNotEmpty();
    }

    public function getRecommendedImageOrderText(): string
    {
        return __('smart_image_management.recommended_image_order_text', [
            'integration' => __('integrations.names.' . $this->getEnabledIntegrationKey())
        ]);
    }


    public function getImageOrderAppliedText(): string
    {
        return __('smart_image_management.image_order_applied_text', [
            'integration' => __('integrations.names.' . $this->getEnabledIntegrationKey())
        ]);
    }

    public function getKeyImagesText(): string
    {
        return __('smart_image_management.key_images_text', [
            'integration' => __('integrations.names.' . $this->getEnabledIntegrationKey()),
            'images' => implode(', ', $this->getKeyImages())
        ]);
    }

    public function loadSmartImageManagementData(Vehicle|VehicleOffer $model): void
    {
        $this->data = $this->getDriver()->getSmartImageManagementData($model);
    }

    public function getKeyImages(): array
    {
        return $this->data['key_images'] ?? [];
    }

    public function getRecommendedImageOrder(): array
    {
        return collect($this->data['recommended_image_order'] ?? [])
            ->sortBy('order')
            ->values()
            ->map(fn (MediaUse $mediaUse) => new MediaEntryResource($mediaUse))
            ->toArray();
    }

    public function getError(): string
    {
        return !empty($this->data['error'] ?? null)
            ? __('smart_image_management.integration_not_available') . ' ' . $this->data['error']
            : '';
    }

    protected function getDriver(): SmartImageManagementDriver
    {
        return $this->driver ?? $this->initializeDriver();
    }

    protected function initializeDriver(): SmartImageManagementDriver
    {
        return $this->getEnabledIntegrations()
            ->map(fn ($integration) => App::make($integration['class']))
            ->firstOrFail();
    }

    protected function getEnabledIntegrationKey(): string
    {
        return $this->getEnabledIntegrations()
            ->keys()
            ->first();
    }

    protected function getEnabledIntegrations(): \Illuminate\Support\Collection
    {
        return new IntegrationRepository()->getEnabledForType('smart-image-management')
            ->filter(fn ($integration) => App::make($integration['class']) instanceof SmartImageManagementDriver);
    }
}
