<?php

namespace boru\boruai\Openai\Stream\Listener;

use boru\boruai\Openai\Stream\AbstractStreamEventListener;
use boru\boruai\Openai\Stream\StreamEvent;

class CompletionStatusListener extends AbstractStreamEventListener
{
    /** @var bool */
    private $completed = false;

    /** @var bool */
    private $failed = false;

    /** @var mixed */
    private $errorPayload = null;

    public function handle(StreamEvent $event)
    {
        $type = $event->type();

        if ($type === StreamEvent::RESPONSE_COMPLETED) {
            $this->completed = true;
            return true;
        }

        if ($type === StreamEvent::RESPONSE_ERROR || $type === StreamEvent::RESPONSE_FAILED) {
            $this->failed = true;
            $method = "error"; // Use variable method name to avoid IDE warnings
            if (method_exists($event, $method)) {
                $this->errorPayload = $event->$method();
            }
            return true;
        }

        return false;
    }

    public function isCompleted()
    {
        return $this->completed ? true : false;
    }

    public function isFailed()
    {
        return $this->failed ? true : false;
    }

    public function getErrorPayload()
    {
        return $this->errorPayload;
    }
}
