<?php

namespace Modules\Auth\Actions\Fortify;

use App\Support\AuthCookie;
use Illuminate\Http\JsonResponse;
use Laravel\Fortify\Contracts\LogoutResponse as LogoutResponseContract;

class LogoutResponse implements LogoutResponseContract
{
    /**
     * Create an HTTP response that represents the object.
     *
     * @param  \Illuminate\Http\Request  $request
     */
    public function toResponse($request): JsonResponse
    {
        if ($request->cookie(AuthCookie::originalUserCookieName())) {
            return response()->json([
                'success' => false,
                'message' => 'Sila tamatkan penyamaran sebelum log keluar.',
            ], 400);
        }

        $user = $request->user();

        if ($user) {
            // Delete all tokens for this user to ensure clean logout
            $user->tokens()->delete();
        }

        $response = response()->json([
            'success' => true,
            'message' => 'Logout successful',
        ], 200);

        return AuthCookie::clearAuthCookies($response);
    }
}
