<?php

namespace App\Http\Controllers;

use App\Models\ActivityLog;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ActivityLogController extends Controller
{
    protected function ensureAdmin(Request $request): ?JsonResponse
    {
        $role = Str::lower((string) ($request->user()?->role ?? ''));
        if ($role !== 'admin') {
            return response()->json(['message' => 'Unauthorized.'], 403);
        }

        return null;
    }

    public function index(Request $request): JsonResponse
    {
        if ($unauthorized = $this->ensureAdmin($request)) {
            return $unauthorized;
        }

        $limit = min(max((int) $request->integer('limit', 15), 1), 100);
        $query = ActivityLog::query()->latest('id');

        if ($request->filled('start_date')) {
            $query->whereDate('created_at', '>=', $request->input('start_date'));
        }

        if ($request->filled('end_date')) {
            $query->whereDate('created_at', '<=', $request->input('end_date'));
        }

        $logs = $query->paginate($limit);

        return response()->json([
            'data' => collect($logs->items())->map(fn (ActivityLog $log) => [
                'id' => $log->id,
                'createdAt' => $log->created_at?->format('Y-m-d h:i:s A'),
                'userName' => $log->user_name,
                'userRole' => $log->user_role,
                'method' => $log->method,
                'actionLabel' => $log->action_label ?: match (strtoupper((string) $log->method)) {
                    'POST' => 'Created',
                    'PATCH', 'PUT' => 'Updated',
                    'DELETE' => 'Deleted',
                    default => (string) $log->method,
                },
                'path' => $log->path,
                'targetType' => $log->target_type,
                'targetId' => $log->target_id,
                'targetUserName' => $log->target_user_name,
                'description' => $log->description ?: 'Updated record data.',
                'statusCode' => $log->status_code,
                'changes' => $log->changes,
            ])->values(),
            'meta' => [
                'currentPage' => $logs->currentPage(),
                'lastPage' => $logs->lastPage(),
                'perPage' => $logs->perPage(),
                'total' => $logs->total(),
            ],
        ]);
    }

    public function destroyAll(Request $request): JsonResponse
    {
        if ($unauthorized = $this->ensureAdmin($request)) {
            return $unauthorized;
        }

        $deleted = ActivityLog::query()->delete();

        return response()->json([
            'message' => 'Logs cleared successfully.',
            'deleted' => $deleted,
        ]);
    }
}
