<?php

namespace App\Services;

use App\Http\Requests\BulkDeleteRequest;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;

class BulkDeleteService
{
    public function delete(BulkDeleteRequest $request): JsonResponse
    {
        $modelClass = $request->getClass();
        $deletedCount = $modelClass::query()
            ->whereIn('id', $request->input('ids'))
            ->get()
            // Do this individually as each model may have their delete hooks which do not execute in query delete
            ->filter(fn(Model $record) => $record->delete())
            ->count();

        return response()->json([
            'message' => "$deletedCount records deleted successfully.",
            'deleted_count' => $deletedCount,
        ]);
    }
}
