<?php

namespace App\Services;

use App\Models\Page;
use App\Models\TranslatedPage;
use App\Services\TranslationDiff\BaseTranslationDiffService;

class PageTranslationDiffService extends BaseTranslationDiffService
{
    public function diff(
        Page $franchisePage,
        Page $globalPage,
        TranslatedPage $franchiseTranslation,
        TranslatedPage $globalTranslation,
    ): array {
        $left = $this->makeSnapshotModel($franchisePage, $franchiseTranslation);
        $right = $this->makeSnapshotModel($globalPage, $globalTranslation);

        $changes = $this->buildDiff($left, $right);

        return array_values(array_filter($changes, function (array $row): bool {
            return !$this->isNoiseDiffField((string) ($row['field'] ?? ''));
        }));
    }

    private function isNoiseDiffField(string $field): bool
    {
        if ($field === 'status' || str_contains($field, 'created_at') || str_contains($field, 'updated_at')) {
            return true;
        }

        if (preg_match('/(^|\.)(source_global_|adopted_from_global|last_local_edit_at|approved_at|approval_status|pending_approval|submitted_for_approval_at)(\.|$)/i', $field)) {
            return true;
        }

        return (bool) preg_match('/\.(checked|required|is_global)$/i', $field);
    }

    protected function includedFields(): array
    {
        return [
            'title',
            'slug',
            'seo_title',
            'seo_description',
            'translated_content',
        ];
    }

    protected function excludedFields(): array
    {
        return [
            'page_id',
            'language_code',
            'is_global_suggestion',
        ];
    }

    protected function fieldLabels(): array
    {
        return [
            'title' => 'Title',
            'slug' => 'Slug',
            'seo_title' => 'SEO Title',
            'seo_description' => 'SEO Description',
            'status' => 'Status',
        ];
    }

    private function makeSnapshotModel(Page $page, TranslatedPage $translation): TranslatedPage
    {
        $model = new TranslatedPage;
        $model->exists = true;
        $model->setAttribute('title', $page->title);
        $model->setAttribute('slug', $page->slug);
        $model->setAttribute('translated_content', $translation->translated_content);
        $model->setAttribute('seo_title', $translation->seo_title);
        $model->setAttribute('seo_description', $translation->seo_description);
        $model->setAttribute('status', $translation->status);

        return $model;
    }
}
