<?php

namespace App\Services;

use App\Http\Resources\DetailPriceListCustomerResource;
use App\Models\DetailPriceListCustomer;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

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

    public function list($withPagination)
    {
        $detailPriceListCustomer = DetailPriceListCustomer::priceListCustomerFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

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

        $detailPriceListCustomer = DetailPriceListCustomerResource::collection($detailPriceListCustomer->load('pricelist', 'customer', 'company'));

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

    public function register($params)
    {
        DB::beginTransaction();
        try {
            # Verificar duplicidad de sucursal
            $customerExisting = DetailPriceListCustomer::customerID($params['idpricelist'], $params['idcustomer'])->active()->first();
            if ($customerExisting) return $this->errorResponse('Cliente ya se encuentra registrado a esta lista de precio.', 400);

            $detailPriceListCustomer = DetailPriceListCustomer::create($params);
            $detailPriceListCustomer->fresh();

            DB::commit();
            return $this->successResponse('cliente agregado a  la lista de precio satisfactoriamente.', $detailPriceListCustomer);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la asignacion de un cliente a una lista de precio.', $th->getMessage());
        }
    }

    public function update($id, $params)
    {
        DB::beginTransaction();
        try {
            # Verificar validez de la lista de precio
            $validate = $this->verifyPriceListCustomer($id, $params['idcustomer']);
            if (!$validate->original['status']) return $validate;

            $detailPriceListCustomer = DetailPriceListCustomer::find($id);
            $detailPriceListCustomer->update($params);

            DB::commit();
            return $this->successResponse('Cliente actualizado de lista de precio satisfactoriamente.', $detailPriceListCustomer);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la actualización de un cliente de una lista de precio.', $th->getMessage());
        }
    }

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

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

            DB::commit();
            return $this->successResponse('Cliente eliminado de lista de precio satisfactoriamente.', $detailPriceListCustomer);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la eliminación de un cliente de una lista de precio.', $th->getMessage());
        }
    }

    private function verifyPriceListCustomer($id, $segment = null)
    {
        $detailPriceListCustomer = DetailPriceListCustomer::activeForID($id)->first();
        if (!$detailPriceListCustomer) return $this->errorResponse('El cliente seleccionado no esta disponible en esta lista de precio', 400);

        if(isset($segment)){
            $validateBranchOffice = DetailPriceListCustomer::customerID($detailPriceListCustomer->idpricelist, $segment, $id)->active()->first();
            if ($validateBranchOffice) return $this->errorResponse('El cliente ya se encuentra registrado.', 400);
        }

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