<?php

namespace App\Repositories\Admin;

use App\Models\Review;
use App\Repositories\Interfaces\Admin\ReviewInterface;
use Exception;
use Illuminate\Support\Facades\Log;

class ReviewRepository implements ReviewInterface
{
    public function createFor($reviewable, array $request)
    {
        $data = [
            'review' => $request['review'],
            'rating' => $request['rating'],
            'user_id' => isset($request['user_id']) ? $request['user_id'] : auth()->id()
        ];
        return $reviewable->reviews()->create($data);
    }

    public function updateReply(int $id, string $reply)
    {
        try {
            $review = Review::findOrFail($id);
            $review->reply = $reply;
            $review->save();

            return $review;
        } catch (Exception $e) {
            Log::error('Updating review reply failed', ['id' => $id, 'error' => $e->getMessage()]);
            throw new Exception('Could not update reply.');
        }
    }

    public function delete(int $id)
    {
        try {
            $review = Review::findOrFail($id);
            return $review->delete();
        } catch (Exception $e) {
            Log::error('Deleting review failed', ['id' => $id, 'error' => $e->getMessage()]);
            throw new Exception('Could not delete review.');
        }
    }

    public function getById(int $id)
    {
        try {
            return Review::findOrFail($id);
        } catch (Exception $e) {
            Log::error('Fetching review failed', ['id' => $id, 'error' => $e->getMessage()]);
            throw new Exception('Review not found.');
        }
    }
}