<?php

namespace App;

use App\Contracts\InteractsWithContentSync;
use Illuminate\Support\Arr;
use Mtc\ContentManager\Facades\Media;
use Mtc\MercuryDataModels\Franchise;

class FranchiseRepository implements InteractsWithContentSync
{
    public function getEnabled(): array
    {
        return Franchise::query()
            ->with('mediaUses.media')
            ->get()
            ->map(fn(Franchise $franchise) => [
                'title' => $franchise->name,
                'colour' => $franchise->primary_colour,
                'link' => '/manage-content/franchises/edit/' . $franchise->id,
                'image' => [
                    'src' => $franchise->mediaUses()
                        ->orderBy('primary')
                        ->first()
                        ?->media
                        ->getSquareThumbUrlAttribute(),
                    'alt' => $franchise->name,
                ]
            ])
            ->toArray();
    }

    public function importRecord(array $entry): bool
    {
        $franchise = Franchise::query()->create(Arr::only($entry, (new Franchise())->getFillable()));

        if (!empty($entry['logo'])) {
            $media = Media::importImageFromUrl($entry['logo']);
            Media::setUsesForModel([$media->id], $franchise, ['primary' =>  true], false);
        }

        if (!empty($entry['square_logo'])) {
            $media = Media::importImageFromUrl($entry['square_logo']);
            Media::setUsesForModel([$media->id], $franchise, ['square' => true], false);
        }

        return $franchise->exists;
    }

    public function canBeImported(array $entry): bool
    {
        return !Franchise::query()
            ->where('slug', $entry['slug'])
            ->exists();
    }

    public function exportToRemote(array $selections): array
    {
        return Franchise::query()
            ->with('mediaUses.media')
            ->whereIn('id', $selections)
            ->get()
            ->map(function ($franchise) {
                $franchiseData = $franchise->toArray();

                $franchiseData['logo'] = $franchise->mediaUses
                    ->filter(fn ($mediaUse) => $mediaUse->primary ?? null)
                    ->first()
                    ?->media
                    ->getOriginalUrlAttribute();

                $franchiseData['square_logo'] = $franchise->mediaUses
                    ->filter(fn ($mediaUse) => $mediaUse->flags['square'] ?? null)
                    ->first()
                    ?->media
                    ->getOriginalUrlAttribute();

                unset($franchiseData['media_uses']);

                return $franchiseData;
            })
            ->toArray();
    }

    public function checkImportEntryValidity(array $dataEntry, array $allEntries): array
    {
        $errors = [];

        if (empty($dataEntry['slug'])) {
            $errors[] = __('validation.import_slug_missing', ['slug' => $dataEntry['slug']]);
        } elseif (Franchise::query()->where('slug', $dataEntry['slug'])->exists()) {
            $errors[] = __('validation.import_slug_taken', ['slug' => $dataEntry['slug']]);
        }

        return [
            'data' => $dataEntry,
            'errors' => $errors,
        ];
    }
}
