<?php

namespace Modules\Auth\Services;

use App\Services\ActiveRoleService;
use App\Support\AuthCookie;
use Illuminate\Http\JsonResponse;
use Modules\Auth\Entities\User;
use Modules\Auth\Transformers\UserResource;

class AuthSessionService
{
    public function createAuthResponse(User $user, string $message, int $status = 200): JsonResponse
    {
        if (config('app.env') !== 'local') {
            $user->tokens()->delete();
        }

        $token = $user->createToken(
            name: 'authToken',
            abilities: ['*'],
            expiresAt: now()->addMinutes((int) config('auth_cookie.lifetime_minutes', 720))
        );

        $user->load(['roles.permissions']);

        ActiveRoleService::assignDefaultToToken($user, $token->accessToken);

        $payload = [
            'success' => true,
            'message' => $message,
            'data' => [
                'user' => new UserResource($user),
                'token' => $token->plainTextToken,
                'token_type' => 'Bearer',
                'expires_at' => $token->accessToken->expires_at,
            ],
            ...ActiveRoleService::sessionMeta($user),
        ];

        if (AuthCookie::shouldExposeTokenInResponse()) {
            $payload['data']['token'] = $token->plainTextToken;
        }

        $response = response()->json($payload, $status);

        return AuthCookie::attachAuthToken($response, $token->plainTextToken);
    }
}
