import { IConnectContext, IMiddleware } from '@mescius/js-collaboration';
import { DocServices } from '../services/doc.mjs';
import { UserServices } from '../services/user.mjs';
import { Role } from '../db/doc-user-role.mjs';

export function connectionAuth(userServices: UserServices, docServices: DocServices): IMiddleware<IConnectContext> {
    return async (context, next) => {
        const { token } = context.connection.auth;

        try {
            const user = await userServices.verifyToken(token as string);
            if (!user) {
                return await next('Unauthorized');
            }
            const role = await docServices.getRole(user.id, context.roomId);
            if (role === Role.none) {
                return await next('Unauthorized');;
            }

            context.connection.tags.set('user', { ...user, role });
            await next();
        } catch (error) {
            await next('Unauthorized');
        }
    };
}
