<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\LinkCode;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class LinkAccountController extends Controller
{
    /**
     * Redeems a code the player generated on their Profile page (see
     * Player\ProfileController::generateLinkCode) from the /linkucp
     * in-game command, attaching their FiveM license to the UCP account
     * without the resource ever needing to know the account's password or
     * Discord token.
     */
    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'code' => ['required', 'string', 'size:8'],
            'license' => ['required', 'string', 'max:100'],
        ]);

        $linkCode = LinkCode::query()
            ->where('code', strtoupper($data['code']))
            ->where('expires_at', '>', now())
            ->first();

        if (! $linkCode) {
            return response()->json(['linked' => false, 'message' => 'Invalid or expired code.'], 422);
        }

        $linkCode->user->update(['fivem_license' => $data['license']]);
        $linkCode->delete();

        return response()->json(['linked' => true]);
    }
}
