package de.cannamanage.api.security;

import de.cannamanage.domain.entity.TenantContext;
import jakarta.persistence.EntityManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.hibernate.Session;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * CRITICAL FIX: Activates the Hibernate @Filter("tenantFilter") on every repository call.
 * Without this, the filter defined on AbstractTenantEntity is never enabled,
 * meaning ALL queries return data across ALL tenants — a severe data leak.
 *
 * This aspect intercepts every Spring Data JPA repository method and enables
 * the tenant filter with the current tenant ID from TenantContext.
 */
@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class TenantFilterAspect {

    private final EntityManager entityManager;

    @Before("execution(* de.cannamanage.service.repository.*.*(..))")
    public void activateTenantFilter() {
        UUID tenantId = TenantContext.getCurrentTenant();
        if (tenantId == null) {
            log.trace("No tenant in context — filter not activated (public endpoint or system call)");
            return;
        }

        Session session = entityManager.unwrap(Session.class);
        session.enableFilter("tenantFilter")
                .setParameter("tenantId", tenantId);
        log.trace("Tenant filter activated for tenant {}", tenantId);
    }
}
