<?php
declare(strict_types = 1);

namespace BewitchingSource\CreamailerAPI;

use GuzzleHttp\Client;

use BewitchingSource\CreamailerAPI\Lists as Lists;
use BewitchingSource\CreamailerAPI\Subscribers as Subscribers;
use BewitchingSource\CreamailerAPI\Suppressions as Suppressions;
use BewitchingSource\CreamailerAPI\ConnectionTest as ConnectionTest;

class API {

    public object $api_settings;
    public array $guzzle_settings;
    public Client $client;
    public Lists $Lists;
    public Subscribers $Subscribers;
    public Suppressions $Suppressions;
    public ConnectionTest $ConnectionTest;

    public function __construct(string $key, string $shared_key) {
        $api_url = "https://api.cmfile.net/v1/api/";
        $this->api_settings = (object)[
            "url" => $api_url,
            "key" => $key,
            "shared_key" => $shared_key
        ];
        $this->guzzle_settings = [
            "base_uri" => $api_url,
        ];
        $this->client = new \GuzzleHttp\Client($this->guzzle_settings);
        $this->init_resources();
    }

    public function init_resources() {
        $this->Lists = new Lists($this);
        $this->Subscribers = new Subscribers($this);
        $this->Suppressions = new Suppressions($this);
        $this->ConnectionTest = new ConnectionTest($this);
    }

    public function checksum(string $uri, array $payload, string $timestamp): string {
        $json = empty($payload)
            ? null
            : \json_encode($payload);

        return sha1($uri
                   .$json
                   .$timestamp
                   .$this->api_settings->shared_key);
    }

    public function headers(string $uri, array $payload): array {
        $timestamp = time();

        return [
            "headers" => [
                "Accept" => "application/json",
                "Content-Type" => "application/json; charset=UTF-8",
                "X-Access-Token" => $this->api_settings->key,
                "X-Request-Signature" => $this->checksum($uri, $payload, (string)$timestamp),
                "X-Request-Timestamp" => (string)$timestamp
            ]
        ];
    }
}
