<?php

namespace App\Services;

use App\Http\Resources\DetailPriceListSalesmanResource;
use App\Models\DetailPriceListSalesman;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

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

    public function list($withPagination)
    {
        $detailPriceListSalesman = DetailPriceListSalesman::priceListSalesmanFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

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

        $detailPriceListSalesman = DetailPriceListSalesmanResource::collection($detailPriceListSalesman->load('pricelist', 'salesman', 'company'));

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

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

            $detailPriceListSalesman = DetailPriceListSalesman::create($params);
            $detailPriceListSalesman->fresh();

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

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

            $detailPriceListSalesman = DetailPriceListSalesman::find($id);
            $detailPriceListSalesman->update($params);

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

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

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

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

    private function verifyPriceListSalesman($id, $salesman = null)
    {
        $detailPriceListSalesman = DetailPriceListSalesman::activeForID($id)->first();
        if (!$detailPriceListSalesman) return $this->errorResponse('El vendedor seleccionado no esta disponible en esta lista de precio', 400);

        if(isset($salesman)){
            $validateBranchOffice = DetailPriceListSalesman::salesmanID($detailPriceListSalesman->idpricelist, $salesman, $id)->active()->first();
            if ($validateBranchOffice) return $this->errorResponse('El vendedor ya se encuentra registrado.', 400);
        }

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