import { CanActivate, ExecutionContext, ForbiddenException, Injectable, UnauthorizedException } from '@nestjs/common';
import { Request } from 'express';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class WebAuthGuard implements CanActivate {
    constructor(private prismaService: PrismaService) {}

    async canActivate(context: ExecutionContext): Promise<boolean> {
        const req: Request = context.switchToHttp().getRequest();

        const token = req.headers.authorization;

        if (!token) throw new UnauthorizedException();

        const group = await this.prismaService.group.findFirst({
            where: { slug: token },
        });

        if (!group) throw new ForbiddenException();

        req.group = group;

        return true;
    }
}