<?php

namespace App\Services\ImportExport\Handlers;

use App\Models\AuditLog;

class AuditLogsHandler extends AbstractModuleHandler
{
    public function key(): string
    {
        return 'audit-logs';
    }

    public function label(): string
    {
        return 'Audit Trail';
    }

    public function permissionModule(): string
    {
        return 'reports';
    }

    public function exportData(array $filters): array
    {
        $query = AuditLog::query()->with('user')->latest();

        if ($event = ($filters['event'] ?? null)) {
            $query->where('event', $event);
        }

        if ($from = ($filters['from'] ?? null)) {
            $query->whereDate('created_at', '>=', $from);
        }

        if ($to = ($filters['to'] ?? null)) {
            $query->whereDate('created_at', '<=', $to);
        }

        $logs = $query->limit(5000)->get();

        return [
            'title' => 'Audit Trail Export',
            'sheet_name' => 'Audit Logs',
            'headings' => ['Date/Time', 'User', 'Event', 'Model', 'Model ID', 'IP Address'],
            'rows' => $logs->map(fn (AuditLog $log) => [
                optional($log->created_at)->format('Y-m-d H:i:s'),
                $log->user?->name ?? 'System',
                $log->event,
                class_basename($log->auditable_type ?? ''),
                $log->auditable_id,
                $log->ip_address,
            ])->all(),
            'filters' => $this->filterSummary($filters),
            'totals' => ['Records' => $logs->count()],
        ];
    }
}
