<?php

namespace App\Services\Facturapi;

use Facturapi\Exceptions\Facturapi_Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Log;

use App\Helpers\Database\SatCatalogsHelper;

class FacturapiProductService extends FacturapiResourceService
{
  //* CRUD Functions
    /**
     * Crear Producto/Servicio
     */
    public function create(array $data): array
    {
        try {
            $payload = $this->parsePayload($data);

            $result = $this->client->Products->create($payload);
            return $this->toArray($result);
        } catch (Facturapi_Exception $e) {
            $this->handleFacturapiException($e);
        }
    }

    /**
     * Obtener Producto/Servicio por ID de Facturapi
     */
    public function retrieve(string $facturapiId): array
    {
        $result = $this->client->Products->retrieve($facturapiId);
        return $this->toArray($result);
    }

    /**
     * Actualizar Producto/Servicio por ID de Facturapi
     */
    public function update(string $facturapiId, array $data): array
    {
        try {
            $payload = $this->parsePayload($data);

            $result = $this->client->Products->update($facturapiId, $payload);
            return $this->toArray($result);
        } catch (Facturapi_Exception $e) {
            $this->handleFacturapiException($e);
        }
    }

    /**
     * Eliminar Producto/Servicio por ID de Facturapi
     */
    public function delete(string $facturapiId): array
    {
        $result = $this->client->Products->delete($facturapiId);
        return $this->toArray($result);
    }


  //* Inherited Functions
    protected function parsePayload(array $form_data): array {
        return [
            "sku"           => $form_data['sku'],
            "description"   => $form_data['name'],

            "product_key"   => $form_data['prod_serv_key'],
            "unit_key"      => $form_data['unit_key'],
            "unit_name"     => $this->sliceUnitName(SatCatalogsHelper::getUnit($form_data['unit_key'])),

            "price"         => $form_data['unit_price'],
            "tax_included"  => $form_data['is_tax_included'],
            "taxability"    => $form_data['object_tax'],

            "taxes"         => $this->parseFederalTaxes($form_data['tax_profile']),
        ];
    }
}
