<?php

namespace App\Framework\Http;

final readonly class RequestBody
{

    public array $data;

    public function __construct(Method $method, Headers $headers, string $body, array $post)
    {

        if ($method === Method::GET) {
            $this->data =  $_GET;
            return;
        }

        $contentType = $headers->get(HeaderKey::CONTENT_TYPE);

        // Prüfen, ob $contentType ein Array ist und konvertiere es ggf. in einen String
        if (is_array($contentType)) {
            $contentType = $contentType[0] ?? '';
        } elseif ($contentType === null) {
            $contentType = '';
        }

        if (str_contains($contentType, MimeType::APPLICATION_JSON->value)) {
            $parsedBody = json_decode($body, true) ?? [];
        } elseif (str_contains($contentType, MimeType::APPLICATION_FORM->value)) {
            parse_str($body, $parsedBody);
        } elseif (str_contains($contentType, MimeType::MULTIPART_FORM_DATA->value)) {
            // Bei multipart/form-data verwende $_POST
            $parsedBody = $post;
        } else {
            // Fallback
            $parsedBody = [];
        }

        $this->data = $parsedBody;
    }

    public function get(string $key, mixed $default = null): mixed
    {
        return $this->data[$key] ?? $default;
    }
}
