<?php

namespace Shikiryu\Bot;

use JsonException;

class Request
{
    public string $nc_signature;
    public string $nc_random;
    public string $nc_server;
    public string $delivery;
    public string $event;
    public string $signature;
    public string $body;
    public array $config;

    public function __construct(array $config = [])
    {
        $this->nc_signature = $_SERVER['HTTP_X_NEXTCLOUD_TALK_SIGNATURE'] ?? '';
        $this->nc_random = $_SERVER['HTTP_X_NEXTCLOUD_TALK_RANDOM'] ?? '';
        $this->nc_server = $_SERVER['HTTP_X_NEXTCLOUD_TALK_BACKEND'] ?? '';

        $this->delivery = $_SERVER['HTTP_X_H1_DELIVERY'] ?? '';
        $this->event = $_SERVER['HTTP_X_H1_EVENT'] ?? '';
        $this->signature = $_SERVER['HTTP_X_H1_SIGNATURE'] ?? '';
        $this->body = file_get_contents('php://input');
        $this->config = $config;
    }

    public function isValid(): bool
    {
        return hash_equals(
            hash_hmac('sha256', $this->nc_random . $this->body, $this->config['secret']),
            strtolower($this->nc_signature)
        );
    }

    public function getJSONBody(): array
    {
        try {
            return json_decode($this->body, true, 512, JSON_THROW_ON_ERROR);
        } catch (JsonException $e) {
            return [];
        }
    }

    public function isMessage(): bool
    {
        $data = $this->getJSONBody();
        return $data['type'] === 'Create' &&
            $data['object']['name'] === 'message' &&
            !empty($data['object']['content']);
    }

    public function getMessage(): string
    {
        try {
            $data = $this->getJSONBody();
            return json_decode($data['object']['content'], true, 512, JSON_THROW_ON_ERROR)['message'];
        } catch (JsonException $e) {
            return '';
        }
    }
}