<?php

namespace adrienpayet\notifications\providers;

use adrienpayet\notifications\NotificationProvider;
use Kirby\Cms\Page;
use Kirby\Cms\User;
use Kirby\Data\Yaml;

/**
 * Provider pour les notifications de type "comment-reply".
 * Collecte les réponses aux commentaires depuis les fichiers.
 */
class ReplyProvider implements NotificationProvider
{
    public function getType(): string
    {
        return 'comment-reply';
    }

    public function collect(Page $project, User $user): array
    {
        $notifications = [];
        $userUuid = (string) $user->uuid();

        // Parcourir toutes les étapes du projet
        foreach ($project->children() as $step) {
            $this->collectFromPage($step, $project, $userUuid, $notifications);

            // Parcourir aussi les sous-pages (ex: tracks)
            foreach ($step->children() as $subPage) {
                $this->collectFromPage($subPage, $project, $userUuid, $notifications);
            }
        }

        return $notifications;
    }

    private function collectFromPage(Page $page, Page $project, string $userUuid, array &$notifications): void
    {
        foreach ($page->files() as $file) {
            if ($file->comments()->isEmpty()) {
                continue;
            }

            $comments = Yaml::decode($file->comments()->value());
            if (!is_array($comments)) {
                continue;
            }

            foreach ($comments as $comment) {
                $replies = $comment['replies'] ?? [];

                foreach ($replies as $reply) {
                    // Ne pas notifier l'auteur de sa propre réponse
                    $authorUuid = $reply['author']['uuid'] ?? '';
                    if ($authorUuid === $userUuid) {
                        continue;
                    }

                    $readby = $reply['readby'] ?? [];

                    $location = $reply['location'] ?? $comment['location'] ?? [];
                    // Assurer que location.project existe toujours
                    if (!isset($location['project'])) {
                        $location['project'] = [
                            'uri' => $project->uri(),
                            'title' => (string) $project->title(),
                        ];
                    }

                    $notifications[] = [
                        'id' => $reply['id'],
                        'type' => 'comment-reply',
                        'text' => $reply['text'] ?? '',
                        'author' => $reply['author'] ?? [],
                        'date' => $reply['date'] ?? '',
                        'location' => $location,
                        'position' => $reply['position'] ?? $comment['position'] ?? [],
                        'readby' => $readby,
                        'isRead' => in_array($userUuid, $readby),
                        // Métadonnées pour markAsRead
                        '_file' => (string) $file->uuid(),
                        '_parentCommentId' => $comment['id'],
                        '_stepUri' => $page->uri(),
                    ];
                }
            }
        }
    }

    public function markAsRead(string $id, array $location, User $user): bool
    {
        $fileUuid = $location['_file'] ?? null;
        $parentCommentId = $location['_parentCommentId'] ?? null;

        if (!$fileUuid) {
            return false;
        }

        // Trouver le fichier par UUID (peut être avec ou sans préfixe file://)
        $fileUri = str_starts_with($fileUuid, 'file://') ? $fileUuid : 'file://' . $fileUuid;
        $file = kirby()->file($fileUri);
        if (!$file) {
            return false;
        }

        $comments = Yaml::decode($file->comments()->value());
        if (!is_array($comments)) {
            return false;
        }

        $userUuid = (string) $user->uuid();
        $updated = false;

        foreach ($comments as &$comment) {
            // Si on a l'ID du parent, l'utiliser pour cibler
            if ($parentCommentId && $comment['id'] !== $parentCommentId) {
                continue;
            }

            $replies = &$comment['replies'] ?? [];

            foreach ($replies as &$reply) {
                if ($reply['id'] === $id) {
                    $reply['readby'] = $reply['readby'] ?? [];
                    if (!in_array($userUuid, $reply['readby'])) {
                        $reply['readby'][] = $userUuid;
                        $updated = true;
                    }
                    break 2;
                }
            }
        }

        if ($updated) {
            $file->update(['comments' => $comments]);
        }

        return $updated;
    }
}
