<?php

namespace App\Services;

use App\Http\Resources\DetailPriceListBranchOfficeResource;
use App\Models\DetailPriceListBranchOffice;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

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

    public function list($withPagination)
    {
        $detailPriceList = DetailPriceListBranchOffice::priceListBranchOfficeFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

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

        $detailPriceList = DetailPriceListBranchOfficeResource::collection($detailPriceList->load('pricelist', 'branchOffice', 'company'));

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

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

            $detailPriceList = DetailPriceListBranchOffice::create($params);
            $detailPriceList->fresh();

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

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

            $detailPriceList = DetailPriceListBranchOffice::find($id);
            $detailPriceList->update($params);

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

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

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

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

    private function verifyPriceListBranchOffice($id, $branchoffice = null)
    {
        $detailPriceList = DetailPriceListBranchOffice::activeForID($id)->first();
        if (!$detailPriceList) return $this->errorResponse('La lista de precio seleccionado no esta disponible en esta sucursal', 400);

        if(isset($branchoffice)){
            $validateBranchOffice = DetailPriceListBranchOffice::branchOfficeID($detailPriceList->idpricelist, $branchoffice, $id)->active()->first();
            if ($validateBranchOffice) return $this->errorResponse('La sucursal ya se encuentra registrado.', 400);
        }

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