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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.acl.custom.initializer.ACLInitializer;
import com.iqser.red.service.persistence.management.v1.processor.dev.DevDataProvider;
import com.iqser.red.service.persistence.management.v1.processor.service.job.AutomaticAnalysisJob;
import com.knecon.fforesight.databasetenantcommons.providers.MigrationService;
import com.knecon.fforesight.tenantcommons.TenantProvider;
import com.knecon.fforesight.tenantcommons.model.UpdateDetailsRequest;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AsyncMigrationStarterService implements MigrationService {

    private final AutomaticAnalysisJob automaticAnalysisJob;
    private final MigrationStarterService migrationStarterService;
    private final ACLInitializer aclInitializer;
    private final TenantProvider tenantProvider;
    private final DevDataProvider devDataProvider;


    public AsyncMigrationStarterService(AutomaticAnalysisJob automaticAnalysisJob,
                                        MigrationStarterService migrationStarterService,
                                        ACLInitializer aclInitializer,
                                        TenantProvider tenantProvider,
                                        @Autowired(required = false) DevDataProvider devDataProvider) {

        this.automaticAnalysisJob = automaticAnalysisJob;
        this.migrationStarterService = migrationStarterService;
        this.aclInitializer = aclInitializer;
        this.tenantProvider = tenantProvider;
        this.devDataProvider = devDataProvider;
    }


    @Async
    public void runForTenant(String tenantId) {

        try {
            automaticAnalysisJob.setSchedulingStopped(true);
            migrationStarterService.runForTenant(tenantId);
            aclInitializer.run();
            automaticAnalysisJob.setSchedulingStopped(false);

            tenantProvider.updateDetails(tenantId, UpdateDetailsRequest.builder().key("persistence-service-ready").value(true).build());

            if (devDataProvider != null) {
                devDataProvider.importDossierTemplatesToTenant(tenantId);
            }

        } catch (Exception e) {
            automaticAnalysisJob.setSchedulingStopped(false);
            throw e;
        }
    }

}
