package com.storycove.service;

import com.storycove.entity.BackupJob;
import com.storycove.repository.BackupJobRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Optional;
import java.util.UUID;

@Service
public class AsyncBackupService {

    private static final Logger logger = LoggerFactory.getLogger(AsyncBackupService.class);

    @Autowired
    private BackupJobRepository backupJobRepository;

    @Autowired
    private AsyncBackupExecutor asyncBackupExecutor;

    /**
     * Start a backup job asynchronously.
     * Returns immediately after creating the job record.
     */
    @Transactional
    public BackupJob startBackupJob(String libraryId, BackupJob.BackupType type) {
        logger.info("Creating backup job for library: {}, type: {}", libraryId, type);

        BackupJob job = new BackupJob(libraryId, type);
        job = backupJobRepository.save(job);

        logger.info("Backup job created with ID: {}. Starting async execution...", job.getId());

        asyncBackupExecutor.executeBackupAsync(job.getId());

        logger.info("Async backup execution triggered for job: {}", job.getId());

        return job;
    }

    /**
     * Get backup job status (used for polling during backup creation).
     */
    public Optional<BackupJob> getJobStatus(UUID jobId) {
        return backupJobRepository.findById(jobId);
    }

    /**
     * Delete a stale or failed backup job record.
     * The actual file (if any) is managed by BackupManagementService.
     */
    @Transactional
    public void deleteBackupJob(UUID jobId) throws IOException {
        Optional<BackupJob> jobOpt = backupJobRepository.findById(jobId);
        if (jobOpt.isEmpty()) {
            throw new IOException("Backup job not found");
        }

        backupJobRepository.delete(jobOpt.get());
        logger.info("Deleted backup job record: {}", jobId);
    }
}
