import {
    CanActivate,
    ExecutionContext,
    Injectable,
    NotFoundException,
    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 NotFoundException('That Group does not exist');

        req.group = group;

        return true;
    }
}