<?php

namespace App\Services;

use App\Models\Unit;
use App\Models\User;
use Illuminate\Validation\ValidationException;

class UnitService
{
    /**
     * @param  array{name: string}  $data
     */
    public function create(User $actor, array $data): Unit
    {
        return Unit::query()->create([
            ...$data,
            'created_by' => $actor->id,
        ]);
    }

    /**
     * @param  array{name?: string}  $data
     */
    public function update(Unit $unit, array $data): Unit
    {
        $unit->update($data);

        return $unit->refresh();
    }

    public function delete(Unit $unit): void
    {
        if ($unit->bookings()->exists()) {
            throw ValidationException::withMessages([
                'unit' => 'Cannot delete a unit type that has bookings.',
            ]);
        }

        $unit->delete();
    }
}
