<?php

namespace Daniv04\HaciendaPackage\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Daniv04\HaciendaPackage\Http\Requests\ElectronicTicketRequest;
use Daniv04\HaciendaPackage\Services\DbService\DbService;
use Daniv04\HaciendaPackage\Services\Providers\ProviderFactoryService;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Daniv04\HaciendaPackage\Http\Resources\ReceiptResource;
use Daniv04\HaciendaPackage\Services\InvoicingService;

class ElectronicTicketController extends BaseController
{

    protected $dbService; 
    protected $providerFactory;
    protected $invoicingService;

    public function __construct(DbService $dbService, ProviderFactoryService $providerFactory, InvoicingService $invoicingService)
    {
        $this->dbService = $dbService;
        $this->providerFactory = $providerFactory;
        $this->invoicingService = $invoicingService;
    }


    public function store(ElectronicTicketRequest $request): JsonResponse
    {
         $result = $this->invoicingService->createAndSendTE($request->validated());
        
        if (!$result['success']) {
            if (isset($result['errors'])) {
                return response()->json([
                    'status' => $result['status_code'] ?? 422,
                    'message' => $result['message'],
                    'errors' => $result['errors']
                ], $result['status_code'] ?? 422);
            }

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

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

    public function getAllTickets(Request $request): JsonResponse
    {
        try {
            $receipts = $this->dbService->getAllReceiptsByType('TE', $request->integer('per_page', 25));

            if($receipts->isEmpty()) {
                return $this->SuccessResponse([], 'No electronic tickets found', 200);
            }

            return $this->PaginatedResponse(ReceiptResource::collection($receipts), 'Electronic tickets retrieved successfully');

        } catch (\Exception $e) {
            Log::error('Error in getAllTickets', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            return $this->ErrorResponse(
                'Error retrieving electronic tickets: ' . $e->getMessage(),
                500
            );
        }
    }
    
}
