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

@Injectable()
export class ActiveCompanyGuard implements CanActivate {
  constructor(private readonly prisma: PrismaService) {}

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

    if (!user?.sub) {
      throw new ForbiddenException('User context missing');
    }

    const dbUser = await this.prisma.user.findUnique({
      where: { id: user.sub },
      include: { company: true },
    });

    if (!dbUser?.company || dbUser.company.status !== 'ACTIVE') {
      throw new ForbiddenException('Company must be active to complete this action');
    }

    return true;
  }
}
