<?php

namespace App\Domains\Auth\Controllers;

use App\Domains\Auth\Requests\GoogleTokenExchangeRequest;
use App\Domains\Auth\Resources\UserResource;
use App\Domains\Auth\Services\GoogleAuthService;
use App\Domains\Cart\Services\GuestCartMergeService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cookie;

class GoogleTokenExchangeController extends Controller
{
    public function __construct(
        private readonly GoogleAuthService $googleAuthService,
        private readonly GuestCartMergeService $guestCartMergeService,
    ) {}

    public function __invoke(GoogleTokenExchangeRequest $request): JsonResponse
    {
        $authentication = $this->googleAuthService->exchange(
            $request->validated('oauth_code'),
            $request->validated('tenant_codigo'),
        );

        $guestTokenCookie = $request->cookie('guest_token');
        $guestToken = is_string($guestTokenCookie) && $guestTokenCookie !== ''
            ? $guestTokenCookie
            : null;
        $this->guestCartMergeService->merge(
            $authentication['tenant_codigo'],
            $authentication['user'],
            $guestToken,
        );

        $response = response()->json([
            'code' => 'auth.login_success',
            'message' => __('api.auth.login_success'),
            'token' => $authentication['token'],
            'token_type' => 'Bearer',
            'user' => UserResource::make($authentication['user']),
        ]);

        if ($guestToken !== null) {
            $response->withCookie(Cookie::forget('guest_token'));
        }

        return $response;
    }
}
