<?php

namespace App\Services;

use App\Http\Resources\MechanicsResource;
use App\Models\Mechanics;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

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

    public function list($withPagination)
    {
        $mechanics = Mechanics::mechanicFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

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

        $mechanics = MechanicsResource::collection($mechanics->load('company'));

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

    public function register($params)
    {
        DB::beginTransaction();
        try {
            # Verificar duplicidad de RUT
            $rutExisting = Mechanics::rut($params['rut'])->first();
            if ($rutExisting) return $this->errorResponse('El rut ya se encuentra registrado.', 400);

            $mechanic = Mechanics::create([
                'rut'           => $params['rut'],
                'name'          => $params['name'],
                'surname'       => $params['surname'],
                'email'         => $params['email'],
                'phone'         => $params['phone'],
                'status_turn'   => isset($params['status_turn']) ? $params['status_turn'] : 0,
                'idcompany'     => $params['idcompany']
            ]);
            $mechanic->fresh();

            # Crear usuario por Observer

            DB::commit();
            return $this->successResponse('Mecánico creado satisfactoriamente.', $mechanic);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la creación de un mecanico.', $th->getMessage());
        }
    }

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

            $mechanic = Mechanics::find($id);
            $mechanic->update($params);

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

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

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

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

    private function verifyMechanic($id, $rut = null)
    {
        $mechanic = Mechanics::activeForID($id)->first();
        if (!$mechanic) return $this->errorResponse('El mecánico seleccionado no esta disponible', 400);

        if(isset($rut)){
            $validateRut = Mechanics::rut($rut, $id)->where('status', 1)->first();
            if ($validateRut) return $this->errorResponse('El rut ya se encuentra registrado.', 400);
        }

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