package com.iqser.red.service.persistence.management.v1.processor.service.job;

import static com.iqser.red.service.persistence.management.v1.processor.utils.TenantUtils.isTenantReadyForPersistence;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.acl.custom.service.CustomPermissionService;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantcommons.TenantProvider;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class SyncUserPermissionsJob implements Job {

    private final CustomPermissionService customPermissionService;

    private final TenantProvider tenantProvider;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        var singleTenant = context.getJobDetail().getJobDataMap() != null ? context.getJobDetail().getJobDataMap().get("tenantId") : null;
        tenantProvider.getTenants().forEach(tenant -> {
            // if it's for a single tenant run only for that one, else run it for all tenants
            if (isTenantReadyForPersistence(tenant) && (tenant.getTenantId().equals(singleTenant) || singleTenant == null)) {
                TenantContext.setTenantId(tenant.getTenantId());
                customPermissionService.syncAllCustomPermissions();
                TenantContext.clear();
            }
        });
    }

}
