<?php

namespace App\Services;

use App\Http\Resources\SalesmanBranchOfficeResource;
use App\Models\SalesmanBranchOffice;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

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

    public function list($withPagination)
    {
        $salesman = SalesmanBranchOffice::salesManBranchOfficeFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

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

        $salesman = SalesmanBranchOfficeResource::collection($salesman->load('salesman', 'branchOffice', 'company'));

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

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

            $salesman = SalesmanBranchOffice::create([
                'idsalesman'        => $params['idsalesman'],
                'idbranchoffice'    => $params['idbranchoffice'],
                'idcompany'         => $params['idcompany']
            ]);
            $salesman->fresh();

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

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

            $salesman = SalesmanBranchOffice::find($id);
            $salesman->update($params);

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

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

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

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

    private function verifySalesmanBranchOffice($id, $branchoffice = null)
    {
        $salesman = SalesmanBranchOffice::activeForID($id)->first();
        if (!$salesman) return $this->errorResponse('El vendedor seleccionado no esta disponible en esta sucursal', 400);

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

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