<?php

namespace Maestro\Core\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Spatie\Activitylog\Models\Activity;

class ActivityLogController extends Controller
{
    /**
     * Paginated activity log (Spatie). GET query: search, event, description, sort_field, sort_order, page, per_page.
     */
    public function index(Request $request): JsonResponse
    {
        abort_unless($request->user()?->can('activitylog.view'), 403);

        $validator = Validator::make($request->all(), [
            'event' => 'nullable|string|max:191',
            'search' => 'nullable|string|max:255',
            'description' => 'nullable|string|max:255',
            'sort_field' => 'nullable|string|in:created_at,description,event,causer_id',
            'sort_order' => 'nullable|string|in:asc,desc',
            'page' => 'nullable|integer|min:1',
            'per_page' => 'nullable|integer|min:1|max:100',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $perPage = (int) ($request->query('per_page', 25));
        $sortField = $request->query('sort_field', 'created_at');
        $sortOrder = $request->query('sort_order', 'desc');

        $query = Activity::query()->with(['causer']);

        if ($request->filled('event')) {
            $query->where('event', $request->query('event'));
        }
        if ($request->filled('search')) {
            $term = '%'.trim((string) $request->query('search')).'%';
            $query->where(function ($q) use ($term): void {
                $q->where('description', 'like', $term)
                    ->orWhere('log_name', 'like', $term)
                    ->orWhere('event', 'like', $term);
            });
        }

        if ($request->filled('description')) {
            $d = '%'.trim((string) $request->query('description')).'%';
            $query->where('description', 'like', $d);
        }

        $query->orderBy($sortField, $sortOrder);

        $paginator = $query->paginate($perPage);

        $data = collect($paginator->items())->map(function (Activity $activity) {
            $causer = $activity->causer;
            $causerPayload = null;
            if ($causer) {
                $causerPayload = [
                    'id' => $causer->getKey(),
                    'name' => $causer->name ?? $causer->email ?? (string) $causer->getKey(),
                    'email' => $causer->email ?? null,
                ];
            }

            return [
                'id' => $activity->id,
                'log_name' => $activity->log_name,
                'description' => $activity->description,
                'event' => $activity->event ?? 'action',
                'subject_type' => $activity->subject_type,
                'subject_id' => $activity->subject_id,
                'causer' => $causerPayload,
                'properties' => $activity->properties,
                'created_at' => $activity->created_at?->toIso8601String(),
            ];
        })->values();

        return response()->json([
            'data' => $data,
            'meta' => [
                'current_page' => $paginator->currentPage(),
                'last_page' => $paginator->lastPage(),
                'per_page' => $paginator->perPage(),
                'total' => $paginator->total(),
                'from' => $paginator->firstItem(),
                'to' => $paginator->lastItem(),
            ],
        ]);
    }
}
