<?php

namespace App\Services;

use App\Models\Post;
use App\Models\User;
use Illuminate\Http\UploadedFile;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Storage;

class PostService
{
    public function paginate(User $user, int $perPage = 10): LengthAwarePaginator
    {
        return Post::with(['user', 'likes.user'])
            ->withCount(['comments', 'likes'])
            ->visibleTo($user)
            ->latest()
            ->paginate($perPage);
    }

    public function create(User $user, array $data, ?UploadedFile $image = null): Post
    {
        $imagePath = null;
        if ($image) {
            $imagePath = $image->store('posts', 'public');
        }

        return Post::create([
            'user_id'    => $user->id,
            'content'    => $data['content'],
            'image_path' => $imagePath,
            'visibility' => $data['visibility'],
        ]);
    }

    public function update(Post $post, array $data): Post
    {
        $post->update($data);
        return $post;
    }

    public function delete(Post $post): void
    {
        if ($post->image_path) {
            Storage::disk('public')->delete($post->image_path);
        }
        $post->delete();
    }
}
