<?php

namespace App\Http\Controllers\Concerns;

use App\Models\AdditionalActivity;
use App\Models\Program;
use Illuminate\Database\Eloquent\Model;

trait BuildsTranslationResetPreview
{
    /**
     * @param  array<int, array<string, mixed>>  $changes
     * @return array<string, mixed>
     */
    protected function formatResetPreviewResponse(
        string $entity,
        string $language,
        array $changes,
        Model $franchiseTranslation,
        Model $globalTranslation,
        int $sourceGlobalVersion,
        int $latestGlobalVersion,
    ): array {
        if ($entity === 'program') {
            $franchiseTranslation->loadMissing('program');
            $globalTranslation->loadMissing('program');
        }

        if ($entity === 'additional_activity') {
            $franchiseTranslation->loadMissing('additionalActivity');
            $globalTranslation->loadMissing('additionalActivity');
        }

        return [
            'entity' => $entity,
            'action' => 'reset_to_global',
            'language' => $language,
            'current' => $this->snapshotTranslationForEntity($entity, $franchiseTranslation),
            'global' => $this->snapshotTranslationForEntity($entity, $globalTranslation),
            'diff' => $changes,
            'changes' => $changes,
            'has_differences' => count($changes) > 0,
            'source_global_version' => $sourceGlobalVersion,
            'latest_global_version' => $latestGlobalVersion,
            'message' => count($changes) === 0
                ? 'Your franchise copy already matches the latest global version for this language.'
                : null,
        ];
    }

    /**
     * @param  array<int, array<string, mixed>>  $changes
     * @return array<int, array<string, mixed>>
     */
    protected function mergeProgramTableResetDiffIntoChanges(Program $franchiseProgram, Program $globalProgram, array $changes): array
    {
        $fieldLabels = [
            'slug' => 'Slug',
            'header_image' => 'Header Image',
            'color' => 'Color',
            'background_color' => 'Background Color',
        ];

        foreach ($fieldLabels as $field => $label) {
            $old = $franchiseProgram->getAttribute($field);
            $new = $globalProgram->getAttribute($field);
            if ((string) ($old ?? '') !== (string) ($new ?? '')) {
                $changes[] = [
                    'field' => $field,
                    'label' => $label,
                    'old' => $old,
                    'new' => $new,
                    'changed' => true,
                    'type' => 'text',
                ];
            }
        }

        return array_values($changes);
    }

    /**
     * @param  array<int, array<string, mixed>>  $changes
     * @return array<int, array<string, mixed>>
     */
    protected function mergeAdditionalActivityTableResetDiffIntoChanges(AdditionalActivity $franchiseActivity, AdditionalActivity $globalActivity, array $changes): array
    {
        $fieldLabels = [
            'slug' => 'Slug',
            'activity_icon' => 'Activity Icon',
        ];

        foreach ($fieldLabels as $field => $label) {
            $old = $franchiseActivity->getAttribute($field);
            $new = $globalActivity->getAttribute($field);
            if ((string) ($old ?? '') !== (string) ($new ?? '')) {
                $changes[] = [
                    'field' => 'activity.'.$field,
                    'label' => $label,
                    'old' => $old,
                    'new' => $new,
                    'changed' => true,
                    'type' => 'text',
                ];
            }
        }

        return array_values($changes);
    }

    /**
     * @return array<string, mixed>
     */
    protected function snapshotTranslationForEntity(string $entity, Model $translation): array
    {
        $keys = match ($entity) {
            'program' => [
                'title', 'sub_heading', 'button_text', 'age_range', 'duration', 'no_of_lessons',
                'description', 'age_text', 'duration_text', 'lesson_duration_text', 'tag',
                'program_icon', 'program_details',
            ],
            'additional_activity' => ['title', 'activity_icon', 'activity_details'],
            'testimonial' => ['parent_name', 'role', 'comment'],
            default => [],
        };

        $out = [];
        foreach ($keys as $k) {
            if (! array_key_exists($k, $translation->getAttributes())) {
                continue;
            }
            $v = $translation->getAttribute($k);
            $out[$k] = $v instanceof \DateTimeInterface ? $v->format(\DateTimeInterface::ATOM) : $v;
        }

        if ($entity === 'program' && $translation->relationLoaded('program') && $translation->program) {
            $prog = $translation->program;
            $out['slug'] = $prog->slug;
            foreach (['header_image', 'color', 'background_color'] as $pk) {
                $out[$pk] = $prog->getAttribute($pk);
            }
        }

        if ($entity === 'additional_activity' && $translation->relationLoaded('additionalActivity') && $translation->additionalActivity) {
            $out['slug'] = $translation->additionalActivity->slug;
        }

        if ($entity === 'testimonial' && array_key_exists('parent_name', $out)) {
            $out['name'] = $out['parent_name'];
        }

        if ($entity === 'testimonial' && array_key_exists('role', $out)) {
            $out['designation'] = $out['role'];
        }

        return $out;
    }
}
