<?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 Daniv04\HaciendaPackage\Exceptions\InvalidReceiptException;
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
    {
        try {
            $result = $this->invoicingService->createAndSendTE($request->validated());
        } catch (InvalidReceiptException $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }

        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
            );
        }
    }
    
}
