<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Service;

use MauticPlugin\DealFlowBundle\Entity\Deal;
use MauticPlugin\DealFlowBundle\Entity\DealAuditEventRepository;
use MauticPlugin\DealFlowBundle\Entity\DealNoteRepository;
use MauticPlugin\DealFlowBundle\Entity\DealTaskRepository;

class DealTimelineBuilder
{
    public function __construct(
        private readonly DealNoteRepository $noteRepository,
        private readonly DealTaskRepository $taskRepository,
        private readonly DealAuditEventRepository $auditRepository,
    ) {
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function build(Deal $deal): array
    {
        $items = [];

        foreach ($this->noteRepository->findByDeal($deal) as $note) {
            $items[] = [
                'type' => 'note',
                'timestamp' => $note->getCreatedAt(),
                'label' => 'Note added',
                'body' => $note->getBody(),
                'meta' => [
                    'sourceType' => $note->getSourceType(),
                    'sourceRef' => $note->getSourceRef(),
                ],
            ];
        }

        foreach ($this->taskRepository->findByDeal($deal) as $task) {
            $items[] = [
                'type' => 'task',
                'timestamp' => $task->getUpdatedAt(),
                'label' => 'Task '.$task->getStatus(),
                'body' => $task->getTitle(),
                'meta' => [
                    'status' => $task->getStatus(),
                    'dueAt' => $task->getDueAt()?->format(DATE_ATOM),
                ],
            ];
        }

        foreach ($this->auditRepository->findByDeal($deal) as $audit) {
            $items[] = [
                'type' => 'audit',
                'timestamp' => $audit->getCreatedAt(),
                'label' => $audit->getEventType(),
                'body' => null,
                'meta' => $audit->getPayload(),
            ];
        }

        usort(
            $items,
            static fn (array $left, array $right): int => $right['timestamp'] <=> $left['timestamp']
        );

        return $items;
    }
}
