import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { PrismaService } from '../../prisma/prisma.service';

/**
 * TenantMiddleware sets the PostgreSQL session variable `app.club_id`
 * based on the authenticated user's clubId from the JWT.
 *
 * This enables Row-Level Security (RLS) policies to automatically
 * filter data by club, ensuring tenant isolation at the database level.
 *
 * Skipped for unauthenticated routes (e.g. /auth/login).
 */
@Injectable()
export class TenantMiddleware implements NestMiddleware {
  constructor(private readonly prisma: PrismaService) {}

  async use(req: Request, _res: Response, next: NextFunction): Promise<void> {
    const user = (req as unknown as Record<string, unknown>).user as
      | { clubId?: string }
      | undefined;

    if (user?.clubId) {
      await this.prisma.setTenantId(user.clubId);
    }

    next();
  }
}
