<?php

namespace App\Services;

use App\Http\Resources\CustomerWalletResource;
use App\Models\CustomerWallet;
use App\Models\Supplier;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

/**
 * Class CustomerWalletService
 * @package App\Services
 */
class CustomerWalletService
{
    use HasResponse;

    public function list($withPagination)
    {
        $customerWallet = CustomerWallet::customerWalletFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

        $customerWallet = !empty($withPagination)
            ? $customerWallet->paginate($withPagination['perPage'], page: $withPagination['page'])
            : $customerWallet->get();

        $customerWallet = CustomerWalletResource::collection($customerWallet->load('supplier', 'salesman', 'account_status', 'branchOffice', 'company'));

        return $this->successResponse('Lectura exitosa.', $customerWallet);
    }

    public function register($params)
    {
        DB::beginTransaction();
        try {
            # Verificar validez del vendedor
            $verifyCustomer = $this->verifyCustomer($params['idsupplier']);
            if (!$verifyCustomer->original['status']) return $verifyCustomer;

            # Verificar duplicidad de Cliente en la cartera
            $supplierExisting = CustomerWallet::customerWalletID($params['idsupplier'], $params['idsalesman'])->active()->first();
            if ($supplierExisting) return $this->errorResponse('El cliente ya se encuentra registrado a tu cartera.', 400);

            $customerWallet = CustomerWallet::create($params);
            $customerWallet->fresh();

            DB::commit();
            return $this->successResponse('Cliente agregado a tu cartera satisfactoriamente.', $customerWallet);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la asignacion del cliente a utu cartera.', $th->getMessage());
        }
    }

    public function update($id, $params)
    {
        DB::beginTransaction();
        try {
            # Verificar validez del vendedor
            $validate = $this->verifySupplierCustomer($id, $params['idsupplier']);
            if (!$validate->original['status']) return $validate;

            $customerWallet = CustomerWallet::find($id);
            $customerWallet->update($params);

            DB::commit();
            return $this->successResponse('Cliente actualizado satisfactoriamente de tu cartera.', $customerWallet);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la actualización del cliente de tu cartera.', $th->getMessage());
        }
    }

    public function delete($id)
    {
        DB::beginTransaction();
        try {
            # Verificar validez del conductor
            $validate = $this->verifySupplierCustomer($id);
            if (!$validate->original['status']) return $validate;

            $customerWallet = CustomerWallet::find($id);
            $customerWallet->update(['status' => 2]);

            DB::commit();
            return $this->successResponse('Cliente eliminado satisfactoriamente de tu cartera.', $customerWallet);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la eliminación del cliente de tu cartera.', $th->getMessage());
        }
    }

    private function verifySupplierCustomer($id, $supplier = null)
    {
        $salesman = CustomerWallet::activeForID($id)->first();
        if (!$salesman) return $this->errorResponse('El cliente seleccionado no esta disponible en tu cartera', 400);

        if(isset($supplier)){
            # Verificar validez del vendedor
            $verifyCustomer = $this->verifyCustomer($supplier);
            if (!$verifyCustomer->original['status']) return $verifyCustomer;

            $validateCustomerWallet = CustomerWallet::customerWalletID($supplier, $salesman->idsalesman, $id)->active()->first();
            if ($validateCustomerWallet) return $this->errorResponse('El cliente ya se encuentra registrado en tu carrera.', 400);
        }

        return $this->successResponse('OK');
    }

    private function verifyCustomer($idcustomer)
    {
        $customer = Supplier::activeForID($idcustomer)->first();
        if ($customer->type == 2) return $this->errorResponse('No es un cliente válido', 400);

        return $this->successResponse('OK');
    }
}
