<?php

namespace Daniv04\HaciendaPackage\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Daniv04\HaciendaPackage\Http\Requests\ElectronicInvoiceRequest;
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 ElectronicInvoiceController 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(ElectronicInvoiceRequest $request): JsonResponse
    {
        try {
            $result = $this->invoicingService->createAndSendFE($request->validated());
        } catch (InvalidReceiptException $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }

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

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

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

            return $this->PaginatedResponse(ReceiptResource::collection($receipts), 'Electronic invoices retrieved successfully');
        } catch (\Exception $e) {
            Log::error('Error in getAllInvoices', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            return $this->ErrorResponse(
                'Error retrieving electronic invoices: ' . $e->getMessage(),
                500
            );
        }
    }
}
