<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\MemberLevel;
use App\Services\MemberLevelService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MemberLevelController extends Controller
{
    public function __construct(private MemberLevelService $svc)
    {
    }

    public function index(): JsonResponse
    {
        $levels = MemberLevel::query()->orderBy('level', 'asc')->get();
        return response()->json(['data' => $levels]);
    }

    public function me(Request $request): JsonResponse
    {
        $user = $request->user();
        if (!$user) {
            return response()->json(['message' => 'Unauthenticated'], 401);
        }
        $current = $this->svc->currentLevel($user);
        $next = $this->svc->nextLevel($user);
        $needed = $next ? max(0, (int) $next->min_points - (int) $user->points) : 0;

        return response()->json([
            'data' => [
                'level' => (int) $user->level,
                'points' => (int) $user->points,
                'current' => $current,
                'next' => $next,
                'points_to_next' => $needed,
            ],
        ]);
    }

    public function adminUpdate(Request $request): JsonResponse
    {
        $payload = $request->validate([
            'levels' => 'required|array|min:1',
            'levels.*.level' => 'required|integer|min:1|max:10',
            'levels.*.name' => 'required|string|max:100',
            'levels.*.min_points' => 'required|integer|min:0',
            'levels.*.color' => 'nullable|string|max:16',
            'levels.*.badge_icon' => 'nullable|string|max:32',
            'levels.*.benefits' => 'nullable|string',
        ]);

        foreach ($payload['levels'] as $row) {
            MemberLevel::query()->updateOrCreate(
                ['level' => $row['level']],
                [
                    'name' => $row['name'],
                    'min_points' => $row['min_points'],
                    'color' => $row['color'] ?? '#888888',
                    'badge_icon' => $row['badge_icon'] ?? null,
                    'benefits' => $row['benefits'] ?? null,
                ],
            );
        }

        return response()->json([
            'data' => MemberLevel::query()->orderBy('level')->get(),
        ]);
    }
}
