<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\EventHandler;

use App\Scolarite\Domain\Event\NoteModifiee;
use App\Scolarite\Domain\Event\NoteSaisie;
use DateTimeImmutable;
use Doctrine\DBAL\Connection;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'event.bus')]
final readonly class GradeEventSubscriber
{
    public function __construct(
        private Connection $connection,
    ) {
    }

    public function __invoke(NoteSaisie|NoteModifiee $event): void
    {
        if ($event instanceof NoteSaisie) {
            $this->handleNoteSaisie($event);
        } else {
            $this->handleNoteModifiee($event);
        }
    }

    private function handleNoteSaisie(NoteSaisie $event): void
    {
        $this->connection->executeStatement(
            'INSERT INTO grade_events (id, grade_id, event_type, old_value, new_value, old_status, new_status, created_by, created_at)
             VALUES (gen_random_uuid(), :grade_id, :event_type, NULL, :new_value, NULL, :new_status, :created_by, :created_at)',
            [
                'grade_id' => (string) $event->gradeId,
                'event_type' => 'note_saisie',
                'new_value' => $event->value,
                'new_status' => $event->status,
                'created_by' => $event->createdBy,
                'created_at' => $event->occurredOn()->format(DateTimeImmutable::ATOM),
            ],
        );
    }

    private function handleNoteModifiee(NoteModifiee $event): void
    {
        $this->connection->executeStatement(
            'INSERT INTO grade_events (id, grade_id, event_type, old_value, new_value, old_status, new_status, created_by, created_at)
             VALUES (gen_random_uuid(), :grade_id, :event_type, :old_value, :new_value, :old_status, :new_status, :created_by, :created_at)',
            [
                'grade_id' => (string) $event->gradeId,
                'event_type' => 'note_modifiee',
                'old_value' => $event->oldValue,
                'new_value' => $event->newValue,
                'old_status' => $event->oldStatus,
                'new_status' => $event->newStatus,
                'created_by' => $event->modifiedBy,
                'created_at' => $event->occurredOn()->format(DateTimeImmutable::ATOM),
            ],
        );
    }
}
