<?php

namespace App\Services\Facturapi;

use Facturapi\Exceptions\Facturapi_Exception;

use Illuminate\Support\Facades\Http;

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

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

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

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

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

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


  //* Inherited Functions
    /**
     *  Parse Request Payload
    */
    protected function parsePayload(array $form_data): array {
        return [
            "email"         => $form_data['email_billing'],
            "phone"         => $form_data['client_phone'],
            "legal_name"    => $form_data['legal_name'],
            "tax_id"        => $form_data['tax_id'],
            "tax_system"    => $form_data['tax_system'],
            "address" => [
                "zip" => $form_data['zip'],
                ... $form_data['tax_address']
            ],
            "default_invoice_use"    => $form_data['cfdi_use'],
        ];
    }

    /**
     *  Get all Organization's Customers
    */
    public function getAllCustomers() : array {
        $response = Http::withToken(
            config('facturapi.secret_keys.' . config('facturapi.mode'))
        )->get('https://www.facturapi.io/v2/customers');

        $response->throw();

        return $response->json();
    }
}
