<?php

namespace Daniv04\HaciendaPackage\Providers\Cyberfuel;

use DateTime;
use Daniv04\HaciendaPackage\Providers\Contracts\ProviderInterface;
use Daniv04\HaciendaPackage\Data\ProviderResponse;
use Daniv04\HaciendaPackage\Providers\Cyberfuel\Transformer\CyberfuelTransformer;
use Daniv04\HaciendaPackage\Services\KeyGeneratorService;
use Illuminate\Support\Facades\Http;

class CyberfuelProvider implements ProviderInterface
{
    public function __construct(
        private KeyGeneratorService $keyGenerator,
    ) {}

    public function sendDocument(array $payload, string $consecutiveNumber): ProviderResponse
    {
        $date = $payload['Encabezado']['FechaEmision'] ?? (new DateTime())->format('Y-m-d\TH:i:sP');
        $dateParsed = $this->keyGenerator->parseDateToArray($date);
        $securityCode = $this->keyGenerator->generateSecurityCode($consecutiveNumber . $date);

        if(in_array($payload['Clave']['TipoComprobante'] ?? '', ['05', '06', '07']))
        {
            $transformedData = CyberfuelTransformer::transformSentDocument($payload, $consecutiveNumber, $dateParsed, $securityCode);
        }
        else
        {
             $transformedData = CyberfuelTransformer::transformDocument($payload, $consecutiveNumber, $dateParsed, $securityCode);
        }

        $baseUrl = config('cyberfuel.api_base_url_stag');
        $methodUrl = config('cyberfuel.makeXml_url_stag');
        $url = $baseUrl . $methodUrl;
        try {
            $response = Http::post($url, $transformedData);

            if (!$response->successful()) {
                return ProviderResponse::failed(
                    errorMessage: 'Provider error HTTP ' . $response->status(),
                    retriable: true,
                    raw: ['body' => $response->body()]
                );
            }

            $responseData = $response->json();
            $code = $responseData['code'] ?? null;

            if ($code === '1') {
                $documentKey = $responseData['clave'] ?? 'unknown-key';
                $sentAt = $responseData['fecha'] ?? $date;

                return ProviderResponse::success(
                    documentKey: $documentKey,
                    sentAt: $sentAt,
                    signedXml: $responseData['data'] ?? null,
                    raw: $responseData
                );
            }

            return ProviderResponse::failed(
                errorMessage: 'Error on sending the document',
                retriable: true,
                raw: $responseData
            );

        } catch (\Exception $e) {
            return ProviderResponse::failed(
                errorMessage: 'Exception on sending the document: ' . $e->getMessage(),
                retriable: true,
                raw: ['trace' => $e->getTraceAsString()]
            );
        }

    }

    

    public function getDocumentStatus(array $documentKey): array
    {
        // Implementación para obtener el estado del documento desde Cyberfuel
        return [];
    }
}