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

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

    async canActivate(context: ExecutionContext): Promise<boolean> {
        const ctx = GqlExecutionContext.create(context);

        const req: Request = ctx.getContext().req;

        const token = req.headers.authorization;

        if (!token) return false;

        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;
    }
}