<?php

namespace MintyPHP\Service\Auth;

use MintyPHP\Curl;

class OidcHttpGateway
{
    /**
     * @param array<string, string> $headers
     */
    public function call(string $method, string $url, mixed $data = '', array $headers = []): array
    {
        return $this->callWithStream(strtoupper($method), $url, $data, $headers);
    }

    /**
     * @param array<string, string> $headers
     */
    private function callWithStream(string $method, string $url, mixed $data, array $headers): array
    {
        $headerLines = [];
        foreach ($headers as $key => $value) {
            $headerLines[] = $key . ': ' . $value;
        }

        $httpContext = [
            'method' => $method,
            'header' => implode("\r\n", $headerLines),
            'ignore_errors' => true,
        ];

        if ($method === 'POST') {
            $body = is_array($data) ? http_build_query($data) : (string) $data;
            $httpContext['content'] = $body;
            if (!isset($headers['Content-Type'])) {
                $httpContext['header'] .= "\r\nContent-Type: application/x-www-form-urlencoded";
            }
        }

        $ctx = stream_context_create([
            'http' => $httpContext,
            'ssl' => [
                'verify_peer' => true,
                'verify_peer_name' => true,
            ],
        ]);

        $body = @file_get_contents($url, false, $ctx);
        $status = 0;
        $responseHeaders = [];
        if (isset($http_response_header) && is_array($http_response_header)) {
            foreach ($http_response_header as $i => $line) {
                if ($i === 0 && preg_match('/HTTP\/[\d.]+ (\d+)/', $line, $m)) {
                    $status = (int) $m[1];
                } elseif (str_contains($line, ': ')) {
                    [$k, $v] = explode(': ', $line, 2);
                    $responseHeaders[$k] = $v;
                }
            }
        }
        return [
            'status' => $status,
            'headers' => $responseHeaders,
            'data' => is_string($body) ? $body : '',
            'url' => $url,
        ];
    }
}
