<?php

namespace App\Http\Controllers\Api\V1\Player;

use App\Support\ApiResponse;
use App\Services\AuditLogger;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Services\Player\PlayerPasswordService;
use App\Http\Requests\Player\PlayerPasswordUpdateRequest;

/** PUT /api/v1/player/password — 彩票端账号自助修改密码 */
final class PlayerPasswordUpdateController extends Controller
{
    public function __invoke(
        PlayerPasswordUpdateRequest $request,
        PlayerPasswordService $passwords,
    ): JsonResponse {
        $player = $request->lotteryPlayer();
        abort_if($player === null, 500, 'lottery_player missing');

        $updated = DB::transaction(function () use ($passwords, $player, $request) {
            $updated = $passwords->change(
                $player,
                (string) $request->validated('current_password'),
                (string) $request->validated('password'),
            );

            AuditLogger::recordForPlayer(
                $updated,
                $request,
                'player_account',
                'change_password',
                'player',
                (string) $updated->id,
                null,
                ['native_token_version' => (int) $updated->native_token_version],
            );

            return $updated;
        });

        return ApiResponse::success(['password_changed' => true], request: $request);
    }
}
