<?php

namespace App\Domains\Auth\Controllers;

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

class LoginController extends Controller
{
    public function __construct(
        private readonly GuestCartMergeService $guestCartMergeService,
        private readonly PasswordLoginService $passwordLoginService,
    ) {}

    public function __invoke(LoginUserRequest $request): JsonResponse
    {
        $credentials = $request->validated();
        $user = $this->passwordLoginService->authenticate(
            $credentials['email'],
            $credentials['password'],
            $credentials['tenant_codigo'],
            $request->ip(),
            $request->userAgent(),
        );

        $expirationMinutes = (int) config('sanctum.expiration');
        $token = $user->createToken(
            'api-token',
            ['*'],
            now()->addMinutes($expirationMinutes),
        )->plainTextToken;

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

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

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

        return $response;
    }
}
