<?php

namespace App\Services;

use App\Models\ReviewImprovement;
use Exception;

class ReviewImprovementService
{
    public function getByReviewId(int $reviewId)
    {
        return ReviewImprovement::with(['improvementType'])
            ->where('review_id', $reviewId)
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function create(array $data): ReviewImprovement
    {
        $existing = ReviewImprovement::where('review_id', data_get($data, 'review_id'))
            ->where('improvement_type_id', data_get($data, 'improvement_type_id'))
            ->first();

        if ($existing) {
            if ($existing->trashed()) {
                $existing->restore();

                return $existing->fresh(['improvementType']);
            } else {
                throw new Exception(__('validation.review_improvement.already_exists'));
            }
        }

        $item = ReviewImprovement::create($data);

        $item->load(['improvementType']);

        return $item;
    }

    public function delete(int $id): bool
    {
        $item = ReviewImprovement::findOrFail($id);

        return $item->delete();
    }
}
