<?php

namespace Daniv04\HaciendaPackage\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Daniv04\HaciendaPackage\Providers\Hacienda\HaciendaProvider;
use Illuminate\Support\Facades\Log;
use Daniv04\HaciendaPackage\Services\InvoicingService;

class HaciendaTestController extends BaseController
{
    public function __construct(
        private InvoicingService $service
    ) {}

    /**
     * Test sending an invoice to Hacienda via Hacienda Provider
     *
     * @param Request $request
     * @return JsonResponse
     *
     * Expected payload structure:
     * {
     *   "consecutive_number": "0000000002",
     *   "payload": { ... invoice data ... }
     * }
     */
    public function sendInvoiceToHacienda(Request $request): JsonResponse
    {
        try {

        
            $result = $this->service->createAndSend('FE',$request->all() );

            if (!$result['success']) {
                Log::warning('Failed to send invoice to Hacienda', [
                    'message' => $result['message'],
                    'errors' => $result['errors'] ?? [],
                ]);

                return $this->ErrorResponse(
                    $result['message'],
                    400
                );
            }

            Log::info('Invoice sent successfully to Hacienda', [
                'data' => $result['data'] ?? [],
            ]);

            return $this->SuccessResponse(
                $result['data'] ?? [],
                $result['message'],
                201
            );

        } catch (\Illuminate\Validation\ValidationException $e) {
            Log::warning('Validation error in sendInvoiceToHacienda', [
                'errors' => $e->errors(),
            ]);

            return response()->json([
                'status' => 422,
                'message' => 'Validation error',
                'errors' => $e->errors()
            ], 422);

        } catch (\Exception $e) {
            Log::error('Exception in sendInvoiceToHacienda', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);

            return $this->ErrorResponse(
                'Error sending invoice to Hacienda: ' . $e->getMessage(),
                500
            );
        }
    }

    /**
     * Simple health check to verify the provider is configured correctly
     */
    public function healthCheck(): JsonResponse
    {
        try {
            // Try to verify that the required services are available
            return $this->SuccessResponse(
                [
                    'status' => 'ok',
                    'provider' => 'Hacienda',
                    'message' => 'Provider is ready to send invoices'
                ],
                'Hacienda test provider is healthy',
                200
            );
        } catch (\Exception $e) {
            return $this->ErrorResponse(
                'Provider health check failed: ' . $e->getMessage(),
                500
            );
        }
    }
}
