<?php

namespace Maestro\Core\Http\Controllers;

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

class ActivityLogController extends Controller
{
    /**
     * List activity log entries. Paginated, optional filters: event, causer_id.
     */
    public function index(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'event' => 'nullable|string|max:50',
            'causer_id' => 'nullable|integer|min:1',
            'search' => '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->input('per_page') ?: 25);
        $sortField = $request->input('sort_field', 'created_at');
        $sortOrder = $request->input('sort_order', 'desc');

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

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

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

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

        $data = $paginator->getCollection()->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(),
            ];
        });

        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(),
            ],
        ]);
    }
}
