<?php

namespace App\Repositories;

use App\Models\ActivityLog;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;

class ActivityLogRepository
{
    public function create(array $attributes): ActivityLog
    {
        return ActivityLog::query()->create($attributes);
    }

    public function paginate(array $filters, int $perPage = 20): LengthAwarePaginator
    {
        return ActivityLog::query()
            ->with(['user', 'website'])
            ->when($filters['category'] ?? null, fn ($query, $category) => $query->where('category', $category))
            ->when($filters['search'] ?? null, function ($query, $search) {
                $query->where(function ($builder) use ($search) {
                    $builder
                        ->where('action', 'like', "%{$search}%")
                        ->orWhere('description', 'like', "%{$search}%")
                        ->orWhereHas('website', fn ($website) => $website->where('name', 'like', "%{$search}%"));
                });
            })
            ->orderByDesc('occurred_at')
            ->paginate($perPage)
            ->withQueryString();
    }

    public function recent(int $limit = 10): Collection
    {
        return ActivityLog::query()
            ->with(['user', 'website'])
            ->latest('occurred_at')
            ->limit($limit)
            ->get();
    }

    public function search(?string $term, int $limit = 8): Collection
    {
        if (! $term) {
            return new Collection();
        }

        return ActivityLog::query()
            ->with(['user', 'website'])
            ->where(function ($query) use ($term) {
                $query
                    ->where('action', 'like', "%{$term}%")
                    ->orWhere('description', 'like', "%{$term}%");
            })
            ->latest('occurred_at')
            ->limit($limit)
            ->get();
    }
}
