<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\Keywords\KeywordQuotaService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdminUserController extends Controller
{
    public function __construct(
        private readonly KeywordQuotaService $keywordQuota
    ) {}

    private function authorizeAdmin(Request $request): ?JsonResponse
    {
        $adminToken = (string) config('dewemoji.admin.token', '');
        $provided = trim((string) $request->header('X-Admin-Token', ''));
        if ($adminToken === '' || $provided === '' || ! hash_equals($adminToken, $provided)) {
            return response()->json(['ok' => false, 'error' => 'unauthorized'], 401);
        }

        return null;
    }

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

        $q = trim((string) $request->query('q', ''));
        $limit = max((int) $request->query('limit', 20), 1);

        $query = User::query()->orderByDesc('id');
        if ($q !== '') {
            $query->where(function ($sub) use ($q): void {
                $sub->where('email', 'like', '%'.$q.'%')
                    ->orWhere('name', 'like', '%'.$q.'%');
            });
        }

        $items = $query->limit($limit)->get(['id', 'name', 'email', 'tier', 'created_at']);

        return response()->json([
            'ok' => true,
            'items' => $items,
        ]);
    }

    public function show(Request $request): JsonResponse
    {
        if ($res = $this->authorizeAdmin($request)) {
            return $res;
        }

        $email = trim((string) $request->query('email', ''));
        $userId = (int) $request->query('user_id', 0);

        $query = User::query();
        if ($email !== '') {
            $query->where('email', $email);
        } elseif ($userId > 0) {
            $query->where('id', $userId);
        } else {
            return response()->json(['ok' => false, 'error' => 'missing_target'], 400);
        }

        /** @var User|null $user */
        $user = $query->first();
        if (! $user) {
            return response()->json(['ok' => false, 'error' => 'not_found'], 404);
        }

        return response()->json([
            'ok' => true,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'tier' => $user->tier,
                'created_at' => $user->created_at,
            ],
        ]);
    }

    public function setTier(Request $request): JsonResponse
    {
        if ($res = $this->authorizeAdmin($request)) {
            return $res;
        }

        $data = $request->validate([
            'email' => 'nullable|email|max:255',
            'user_id' => 'nullable|integer',
            'tier' => 'required|string|in:free,personal',
        ]);

        $query = User::query();
        if (! empty($data['email'])) {
            $query->where('email', $data['email']);
        } elseif (! empty($data['user_id'])) {
            $query->where('id', $data['user_id']);
        } else {
            return response()->json(['ok' => false, 'error' => 'missing_target'], 400);
        }

        /** @var User|null $user */
        $user = $query->first();
        if (! $user) {
            return response()->json(['ok' => false, 'error' => 'not_found'], 404);
        }

        $user->tier = $data['tier'];
        $user->save();
        $this->keywordQuota->enforceForUser((int) $user->id, (string) $user->tier);

        return response()->json([
            'ok' => true,
            'user' => [
                'id' => $user->id,
                'email' => $user->email,
                'tier' => $user->tier,
            ],
        ]);
    }
}
