<?php

namespace Modules\HR\Services\CrossChex;

use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class CrossChexClient
{
    protected string $url;

    public function __construct()
    {
        $this->url = config('hr.crosschex.api_url');
    }

    public function authenticate(): array
    {
        $response = Http::post($this->url, [
            'header' => [
                'nameSpace' => 'authorize.token',
                'nameAction' => 'token',
                'version' => '1.0',
                'requestId' => (string) Str::uuid(),
                'timestamp' => now()->toIso8601String(),
            ],
            'payload' => [
                'api_key'    => config('hr.crosschex.api_key'),
                'api_secret' => config('hr.crosschex.api_secret'),
            ],
        ]);

        if ($response->failed()) {
            throw new \Exception('CrossChex authentication failed.');
        }

        $token = data_get($response->json(), 'payload.token');

        if (! $token) {
            throw new \Exception('CrossChex token not found.');
        }

        return [
            'token' => $token,
            'end_time' => data_get($response->json(), 'header.timestamp'),
        ];
    }

    public function attendanceRecords(
        string $token,
        string $startTime,
        string $endTime
    ): array {
        $response = Http::post($this->url, [
            'header' => [
                'nameSpace' => 'attendance.record',
                'nameAction' => 'getrecord',
                'version' => '1.0',
                'requestId' => (string) Str::uuid(),
                'timestamp' => $startTime,
            ],
            'authorize' => [
                'type'  => 'token',
                'token' => $token,
            ],
            'payload' => [
                'begin_time' => $startTime,
                'end_time'   => $endTime,
                'order'      => 'asc',
                'page'       => 1,
                'per_page'   => 100,
            ],
        ]);

        if ($response->failed()) {
            throw new \Exception('Attendance record fetch failed.');
        }

        return data_get($response->json(), 'payload.list', []);
    }
}
