<?php

namespace App;

use App\Contracts\AbleToSyncContentElements;
use App\Contracts\InteractsWithContentSync;
use Mtc\ContentManager\Contracts\ContentElement as ContentElementContract;
use Mtc\ContentManager\Contracts\ModelWithContent;
use Mtc\MercuryDataModels\ContentElement;
use Mtc\MercuryDataModels\GlobalContent;
use Mtc\MercuryDataModels\Template;

class GlobalContentRepository implements InteractsWithContentSync, AbleToSyncContentElements
{
    public function exportToRemote(array $selections): array
    {
        return GlobalContent::query()
            ->with([
                'contentElement',
            ])
            ->whereIn('id', $selections)
            ->get()
            ->map(function (GlobalContent $globalContent) {
                $data = $globalContent->toArray();
                $data['element_id'] = $globalContent->contentElement?->slug;
                unset($data['content_element']);
                return $data;
            })
            ->toArray();
    }

    public function importRecord(array $entry): bool
    {
        $element = ContentElement::query()
            ->with('fields')
            ->where('slug', $entry['element_id'])
            ->firstOrFail();
        $entry['element_id'] = $element?->id;
        $entry['content'] = collect($entry['content'])
            ->map(fn ($field) => $this->contentFieldIdMap($field, $element))
            ->toArray();

        $globalContent = GlobalContent::query()->create($entry);
        return $globalContent->exists;
    }

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

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

        if ($this->canBeImported($dataEntry) !== true) {
            $errors[] = __('validation.import_global_content_element_missing', [
                'slug' => $dataEntry['element_id'],
                'name' => $dataEntry['name']
            ]);
        }
        return [
            'data' => $dataEntry,
            'errors' => $errors,
        ];
    }

    private function contentFieldIdMap(array $field, ContentElement $element)
    {
        $field['id'] = $element->fields
            ->filter(fn($elementField) => $elementField->slug === $field['slug'])
            ->first()
            ?->id;

        return $field;
    }

    public function isContentElementInSync(ModelWithContent $model, ContentElementContract $element): bool
    {
        return true;
    }

    public function syncElementWithTemplate(int $entry_id, ?ContentElementContract $element = null): void
    {
        // Not needed
    }
}
