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

import java.util.HashSet;
import java.util.Set;

import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.migration.Migration;
import com.iqser.red.service.persistence.management.v1.processor.migration.StorageToMongoCopyService;
import com.mongodb.MongoNamespace;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

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

@Slf4j
@Setter
@Service

public class V24StorageToMongoMigration extends Migration {

    private final StorageToMongoCopyService storageToMongoCopyService;
    private final MongoTemplate mongoTemplate;

    private static final String NAME = "Migration for component log storage from s3 to mongodb";
    private static final long VERSION = 24;


    public V24StorageToMongoMigration(StorageToMongoCopyService storageToMongoCopyService, MongoTemplate mongoTemplate) {

        super(NAME, VERSION);
        this.storageToMongoCopyService = storageToMongoCopyService;
        this.mongoTemplate = mongoTemplate;
    }


    @Override
    protected void migrate() {

        log.info("Renaming collections 'component-logs' and 'component-log-entries' to 'old-component-logs' and 'old-component-log-entries'");

        renameCollection("component-logs", "old-component-logs");
        renameCollection("component-log-entries", "old-component-log-entries");

        log.info("Migration: Copying all component logs for all dossiers to MongoDB");
        storageToMongoCopyService.copyComponentLogs();
    }


    private void renameCollection(String oldName, String newName) {

        MongoDatabase db = mongoTemplate.getDb();
        Set<String> collectionNames = db.listCollectionNames().into(new HashSet<>());
        if (collectionNames.contains(oldName)) {
            MongoCollection<Document> collection = db.getCollection(oldName);
            collection.renameCollection(new MongoNamespace(db.getName(), newName));
            log.info("Renamed collection '{}' to '{}'", oldName, newName);
        } else {
            log.warn("Collection '{}' does not exist, skipping rename", oldName);
        }
    }

}