<?php

namespace App\Services;

use App\Http\Resources\BossMaintenanceResource;
use App\Models\BossMaintenance;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\DB;

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

    public function list($withPagination)
    {
        $bossMaintenance = BossMaintenance::bossMaintenanceFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

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

        $bossMaintenance = BossMaintenanceResource::collection($bossMaintenance->load('company'));

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

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

            $bossMaintenance = BossMaintenance::create([
                'rut'           => $params['rut'],
                'name'          => $params['name'],
                'surname'       => $params['surname'],
                'email'         => $params['email'],
                'phone'         => $params['phone'],
                'idcompany'     => $params['idcompany']
            ]);
            $bossMaintenance->fresh();

            # Crear usuario por Observer

            DB::commit();
            return $this->successResponse('Jefe de mantenimiento creado satisfactoriamente.', $bossMaintenance);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la creación de un jefe.', $th->getMessage());
        }
    }

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

            $bossMaintenance = BossMaintenance::find($id);
            $bossMaintenance->update($params);

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

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

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

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

    private function verifyBossMaintenance($id, $rut = null)
    {
        $bossMaintenance = BossMaintenance::activeForID($id)->first();
        if (!$bossMaintenance) return $this->errorResponse('El Jefe de mantenimiento seleccionado no esta disponible', 400);

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

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