<?php

declare(strict_types=1);

namespace ImovelZapAi\Conversations\Application\Services;

use ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent\ConversationModel;

final class ConversationResponseDelay
{
    public function waitBeforeReply(ConversationModel $conversation): void
    {
        if (! (bool) config('conversations.human_reply_delay.enabled', true)) {
            return;
        }

        /** @var list<int|float|string> $sequence */
        $sequence = config('conversations.human_reply_delay.seconds_sequence', [8, 12, 7, 10, 9]);

        if ($sequence === []) {
            return;
        }

        $context = $conversation->context ?? [];
        $index = (int) ($context['reply_delay_index'] ?? 0);
        $seconds = max(0, (int) $sequence[$index % count($sequence)]);

        $context['reply_delay_index'] = $index + 1;
        $conversation->update(['context' => $context]);

        if ($seconds > 0) {
            sleep($seconds);
        }
    }
}
