<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Client\ConnectionException;

class TartanApiService
{
    private $apiKey;
    private $username;
    private $password;
    private $authUrl;
    private $verifyUrl;
    private $tokenCacheKey = 'tartan_api_token';
    private $tokenValiditySeconds = 18000;

    public function __construct()
    {
        $this->apiKey = config('app.tartan.api_key');
        $this->username = config('app.tartan.username');
        $this->password = config('app.tartan.password');
        $this->authUrl = config('app.tartan.auth_url');
        $this->verifyUrl = config('app.tartan.verify_url');
    }
    
    private function authenticateAndCacheToken(): ?string
    {
        try {
            $response = Http::timeout(60)->withHeaders(['x-api-key' => $this->apiKey])
                ->post($this->authUrl, ['username' => $this->username, 'password' => $this->password]);
            $response->throw();
            $token = $response->json('token');
            if ($token) {
                Cache::put($this->tokenCacheKey, $token, $this->tokenValiditySeconds);
                return $token;
            }
            return null;
        } catch (RequestException | ConnectionException $e) {
            logger()->error('Tartan API authentication failed: ' . $e->getMessage());
            return null;
        }
    }

    public function getValidToken(): ?string
    {
        return Cache::get($this->tokenCacheKey) ?? $this->authenticateAndCacheToken();
    }
    
    public function getVerificationDetails(string $token, string $uan): ?array
    {
        try {
            $response = Http::withToken($token)
                ->timeout(120) 
                ->withHeaders(['x-api-key' => $this->apiKey])
                ->post($this->verifyUrl, [
                    "category" => "employment-verification-unconsented",
                    "type" => "employment-history-from-uan-v2",
                    "applicationId" => "Dashboard-realtime-KYC",
                    "data" => ["uan" => $uan]
                ]);

            $response->throw();
            
            $contentType = $response->header('Content-Type');

            if (str_contains($contentType, 'application/json')) {
                return $response->json();
            }

            if (str_contains($contentType, 'application/pdf')) {
                logger()->error("Verification error for UAN {$uan}: API returned an unexpected PDF file instead of JSON.");
                return ['error' => ['message' => 'The verification service returned an unexpected response type (PDF). Please try again.']];
            }

            logger()->error("Verification error for UAN {$uan}: API returned a non-JSON response. Content-Type: {$contentType}");
            return ['error' => ['message' => 'The verification service returned an invalid response format.']];

        } catch (ConnectionException $e) {
            logger()->error("Verification error for UAN {$uan}: " . $e->getMessage());
            return ['error' => ['message' => 'The verification service took too long to respond (timeout). Please try again.']];
        }
        catch (RequestException $e) {
            logger()->error("Verification error for UAN {$uan}: " . $e->getMessage());
            return $e->response->json() ?? ['error' => ['message' => 'An unknown API error occurred.']];
        }
    }
}