import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService
  extends PrismaClient
  implements OnModuleInit, OnModuleDestroy
{
  async onModuleInit(): Promise<void> {
    await this.$connect();
  }

  async onModuleDestroy(): Promise<void> {
    await this.$disconnect();
  }

  /**
   * Set the club_id for Row-Level Security (RLS) isolation.
   * Must be called at the start of each request via TenantMiddleware.
   */
  async setTenantId(clubId: string): Promise<void> {
    await this.$executeRaw`SET app.club_id = ${clubId}`;
  }

  /**
   * Reset the tenant context (useful for super-admin operations).
   */
  async resetTenantId(): Promise<void> {
    await this.$executeRawUnsafe(`RESET app.club_id`);
  }
}
