<?php

namespace App\Services;

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

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

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

        return $subtype->refresh();
    }

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

        $subtype->delete();
    }
}
