<?php

namespace App\Services;

use App\Models\Like;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;

class LikeService
{
    public function toggle(User $user, Model $model): array
    {
        $morphType = $model->getMorphClass();

        $existing = Like::where([
            'user_id'       => $user->id,
            'likeable_type' => $morphType,
            'likeable_id'   => $model->id,
        ])->first();

        if ($existing) {
            $existing->delete();
            $liked = false;
        } else {
            try {
                Like::create([
                    'user_id'       => $user->id,
                    'likeable_type' => $morphType,
                    'likeable_id'   => $model->id,
                ]);
                $liked = true;
            } catch (\Illuminate\Database\UniqueConstraintViolationException) {
                // Concurrent request already inserted this like; treat as liked.
                $liked = true;
            }
        }

        $likeCount = Like::where([
            'likeable_type' => $morphType,
            'likeable_id'   => $model->id,
        ])->count();

        return ['liked' => $liked, 'like_count' => $likeCount];
    }
}
