<?php

declare(strict_types=1);

namespace App\Application\Actions;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Application\Services\BlogProvider;

class BlogApiPostAction
{
    private BlogProvider $blogProvider;

    public function __construct(BlogProvider $blogProvider)
    {
        $this->blogProvider = $blogProvider;
    }

    public function __invoke(Request $request, Response $response, array $args): Response
    {
        $stub = $args['stub'];

        $article = $this->blogProvider->getByStub($stub);

        if (!$article) {
            $payload = json_encode(['error' => 'Blog post not found']);
            $response->getBody()->write($payload);
            return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
        }

        $payload = json_encode($article);
        $response->getBody()->write($payload);
        return $response->withHeader('Content-Type', 'application/json');
    }
}
