import {
  CanActivate,
  ExecutionContext,
  Inject,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { fromNodeHeaders } from 'better-auth/node';
import type { Auth } from '@mosaicstack/auth';
import type { FastifyRequest } from 'fastify';
import { AUTH } from './auth.tokens.js';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(@Inject(AUTH) private readonly auth: Auth) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest<FastifyRequest>();
    const headers = fromNodeHeaders(request.raw.headers);

    const result = await this.auth.api.getSession({ headers });

    if (!result) {
      throw new UnauthorizedException('Invalid or expired session');
    }

    (request as FastifyRequest & { user: unknown; session: unknown }).user = result.user;
    (request as FastifyRequest & { user: unknown; session: unknown }).session = result.session;

    return true;
  }
}
