<?php

namespace App\Services\Admin\System;

use App\Models\FormHistory;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class FormHistoryService
{
    public function paginated(
        int $perPage = 25,
        string $search = '',
        string $sort = 'created_at',
        string $direction = 'desc',
        array $filters = [],
    ): LengthAwarePaginator {
        return FormHistory::query()
            ->select(['id', 'causer_id', 'module', 'event', 'description', 'attribute_changes', 'created_at'])
            ->with(['causer.userProfile'])
            ->when($search, fn ($q) => $q->where('description', 'like', "%{$search}%"))
            ->when($filters['module'] ?? null, fn ($q, $module) => $q->where('module', $module))
            ->when($filters['event'] ?? null, fn ($q, $event) => $q->where('event', $event))
            ->orderBy($sort, $direction)
            ->paginate($perPage);
    }

    public function getModules(): array
    {
        return FormHistory::query()
            ->distinct()
            ->pluck('module')
            ->sort()
            ->values()
            ->toArray();
    }

    public function getEvents(): array
    {
        return [
            'created' => 'Ditambahkan',
            'updated' => 'Diperbarui',
            'deleted' => 'Dihapus',
        ];
    }
}
