<?php

namespace App\Services;

use App\Http\Resources\DetailPriceListSegmentResource;
use App\Models\DetailPriceListSegment;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

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

    public function list($withPagination)
    {
        $detailPriceListSegment = DetailPriceListSegment::priceListSegmentFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

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

        $detailPriceListSegment = DetailPriceListSegmentResource::collection($detailPriceListSegment->load('pricelist', 'segment', 'company'));

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

    public function register($params)
    {
        DB::beginTransaction();
        try {
            # Verificar duplicidad de sucursal
            $segmentExisting = DetailPriceListSegment::segmentID($params['idpricelist'], $params['idsegment'])->active()->first();
            if ($segmentExisting) return $this->errorResponse('La lista de precio ya se encuentra registrado a este segmento.', 400);

            $detailPriceListSegment = DetailPriceListSegment::create($params);
            $detailPriceListSegment->fresh();

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

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

            $detailPriceListSegment = DetailPriceListSegment::find($id);
            $detailPriceListSegment->update($params);

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

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

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

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

    private function verifyPriceListSegment($id, $segment = null)
    {
        $detailPriceListSegment = DetailPriceListSegment::activeForID($id)->first();
        if (!$detailPriceListSegment) return $this->errorResponse('La lista de precio seleccionado no esta disponible en este segmento', 400);

        if(isset($segment)){
            $validateBranchOffice = DetailPriceListSegment::segmentID($detailPriceListSegment->idpricelist, $segment, $id)->active()->first();
            if ($validateBranchOffice) return $this->errorResponse('El segmento ya se encuentra registrado.', 400);
        }

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