<?php

namespace App\Actions\V1\Service;

use App\Models\Service;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Str;

class UpdateServiceAction
{
    public function execute(int $id, array $data): Service
    {
        $service = Service::find($id);

        if (!$service) {
            throw new ModelNotFoundException("Service not found.");
        }

        if (request()->hasFile('image')) {
            $file = request()->file('image');
            $filename = Str::uuid() . '.' . $file->getClientOriginalExtension();

            $file->move(
                public_path('/storage/uploads/'),
                $filename
            );

            $data['image'] = $filename;
        }

        if (request()->hasFile('icon')) {
            $file = request()->file('icon');
            $filename = Str::uuid() . '.' . $file->getClientOriginalExtension();

            $file->move(
                public_path('storage/uploads/services/icons'),
                $filename
            );

            $data['icon'] = $filename;
        }

        $service->update($data);

        return $service;
    }
}
