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

import org.springframework.beans.factory.annotation.Autowired;

import com.iqser.red.service.persistence.management.v1.processor.service.persistence.MigrationPersistenceService;

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

@Data
@Slf4j
@RequiredArgsConstructor
public abstract class Migration {

    private final String name;
    private final long version;

    @Autowired
    @Setter
    private MigrationPersistenceService migrationPersistenceService;


    public void run() {

        run(false);
    }


    public void run(boolean force) {

        var latestProcessedVersion = migrationPersistenceService.getLatestProcessedVersion();
        if (!migrationPersistenceService.isProcessed(version, latestProcessedVersion) || force) {
            log.info("Starting migration with name {} and version {}", name, version);
            migrate();
            migrationPersistenceService.insertMigration(name, version);
            log.info("Finished migration with name {} and version {}", name, version);
        } else {
            log.info("Migration with name: {} and version {} already done, skipping....", name, version);
        }
    }


    protected abstract void migrate();


    public final long getVersion() {

        return version;
    }

}
