<?php

namespace App\Modules\Admin\ActivityLog\Repositories;

use App\Modules\Admin\ActivityLog\Models\ActivityLog;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
class ActivityLogRepository
{
    /**
     * @param  array{tenant_id?: int|null, module?: string|null, action?: string|null}  $filters
     */
    public function paginate(array $filters, int $perPage = 20): LengthAwarePaginator
    {
        $query = ActivityLog::query()
            ->with([
                'tenant:id,name,slug',
                'user:id,name,email',
            ])
            ->orderByDesc('created_at');

        if (! empty($filters['tenant_id'])) {
            $query->where('tenant_id', (int) $filters['tenant_id']);
        }
        if (! empty($filters['module'])) {
            $query->where('module', (string) $filters['module']);
        }
        if (! empty($filters['action'])) {
            $query->where('action', (string) $filters['action']);
        }

        return $query->paginate($perPage)->withQueryString();
    }

    /**
     * @return array<string, string>
     */
    public function distinctModuleLabels(): array
    {
        return $this->distinctColumnAsOptions('module');
    }

    /**
     * @return array<string, string>
     */
    public function distinctActionLabels(): array
    {
        return $this->distinctColumnAsOptions('action');
    }

    /**
     * @return array<string, string>
     */
    private function distinctColumnAsOptions(string $column): array
    {
        $rows = ActivityLog::query()
            ->select($column)
            ->whereNotNull($column)
            ->where($column, '!=', '')
            ->distinct()
            ->orderBy($column)
            ->pluck($column)
            ->all();

        $out = [];
        foreach ($rows as $value) {
            $key = (string) $value;
            $out[$key] = $key;
        }

        return $out;
    }

    public function insert(array $attributes): ActivityLog
    {
        $attributes['created_at'] ??= now();

        return ActivityLog::query()->create($attributes);
    }
}
