<?php

namespace Daniv04\HaciendaPackage\Http\Controllers;    

use Daniv04\HaciendaPackage\Http\Requests\DocumentReceiptRequest;
use Daniv04\HaciendaPackage\Jobs\SendReceiptToProviderJob;
use Daniv04\HaciendaPackage\Services\DbService\DbService;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class DocumentReceptionController extends BaseController
{

    protected $dbService;
    public function __construct(DbService $dbService)
    {
        $this->dbService = $dbService;
    }

   public function handleReception(DocumentReceiptRequest $request)
    {

        try {
            $validatedData = $request->validated();

            $documentStatus = $this->mapDocumentStatus($validatedData['Detalle']['CodigoMensaje'] ?? null);
            $documentType = $this->mapDocumentType($validatedData['Clave']['TipoComprobante'] ?? null);

            $receipt = $this->dbService->saveSentReceipt($validatedData, $documentStatus, $documentType);

            $provider = config('invoicing.electronic_invoicing_provider');
            SendReceiptToProviderJob::dispatch($receipt, $validatedData, $provider);
            return $this->SuccessResponse(
                [
                    'receipt_id' => $receipt->id,
                    'consecutive_number' => $receipt->consecutive_number,
                    'status' => 'queued',
                    'message' => 'Receipt queued for processing'
                ],
                'Document created successfully and queued for sending to provider',
                201
            );
            //catch validation exceptions from the specific request validation
        } catch (ValidationException $e) {
            return response()->json([
                'status' => 422,
                'message' => 'Validation Error',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            Log::error('Error in DocumentReceptionController', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            return $this->ErrorResponse(
                'Error saving electronic receipt: ' . $e->getMessage(),
                500
            );
        }
    }

    private function mapDocumentStatus($code)
    {
        $status = [
            '1' => 'accepted',
            '2' => 'partially_accepted',
            '3' => 'rejected',
        ];

        return $status[$code] ?? 'unknown';
    }
    private function mapDocumentType($code)
    {
        $types = [

            '05' => 'CA',
            '06' => 'CAP',
            '07' => 'CR',

        ];

        return $types[$code] ?? 'unknown';
    }
}