import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';

export const IS_PUBLIC_KEY = 'isPublic';

@Injectable()
export class WriteKeyGuard implements CanActivate {
  private readonly writeKey: string;

  constructor(private readonly reflector: Reflector) {
    const key = process.env['COLLECTOR_WRITE_KEY'];
    if (!key) {
      throw new Error('COLLECTOR_WRITE_KEY environment variable is required');
    }
    this.writeKey = key;
  }

  canActivate(context: ExecutionContext): boolean {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (isPublic) {
      return true;
    }

    const request = context.switchToHttp().getRequest<Request>();
    const provided = request.headers['x-write-key'];

    if (provided !== this.writeKey) {
      throw new UnauthorizedException('Invalid or missing write key');
    }

    return true;
  }
}
