<?php

declare(strict_types=1);

namespace App\Application\Actions\Content;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use PDO;

class ContentAction
{
    private PDO $pdo;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function __invoke(Request $request, Response $response, array $args): Response
    {
        $key = $args['key'] ?? null;
        $stmt = $this->pdo->prepare('SELECT * FROM contents WHERE key = :key ORDER BY id DESC LIMIT 1');
        $stmt->execute([':key' => $key]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $data = $row['content'] ? json_decode($row['content'], true) : null;
        } else {
            $data = ['error' => 'Not found', 'key' => $key];
        }
        $payload = json_encode($data);
        $response->getBody()->write($payload);
        return $response->withHeader('Content-Type', 'application/json');
    }
}
