import {
    EntitySubscriberInterface,
    EventSubscriber,
    InsertEvent,
    UpdateEvent,
} from 'typeorm';
import { tenantStore } from './tenant.store';

@EventSubscriber()
export class TenantEntitySubscriber implements EntitySubscriberInterface {
    /**
     * Called before entity insertion.
     */
    beforeInsert(event: InsertEvent<any>) {
        this.injectTenantId(event.entity);
    }

    /**
     * Called before entity update.
     */
    beforeUpdate(event: UpdateEvent<any>) {
        this.injectTenantId(event.entity);
    }

    private injectTenantId(entity: any) {
        if (!entity) return;

        // Check if the entity has a tenantId property
        if ('tenantId' in entity) {
            const store = tenantStore.getStore();
            const currentTenantId = store?.tenantId;

            // Only set if it's not already set and we have a tenantId in context
            if (!entity.tenantId && currentTenantId) {
                entity.tenantId = currentTenantId;
            }
        }
    }
}
