package com.yimeng.okr.service;

import com.yimeng.okr.exception.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class DatabaseBackupService {

    private final String datasourceUrl;
    private final String backupDir;

    public DatabaseBackupService(
            @Value("${spring.datasource.url}") String datasourceUrl,
            @Value("${app.backup.dir:./data/backups}") String backupDir) {
        this.datasourceUrl = datasourceUrl;
        this.backupDir = backupDir;
    }

    public Path createBackup() {
        return createBackup("okr-performance");
    }

    public Path createBackup(String label) {
        Path dbPath = resolveSqlitePath(datasourceUrl);
        if (!Files.exists(dbPath)) {
            throw new BusinessException("数据库文件不存在，无法备份: " + dbPath);
        }
        try {
            Files.createDirectories(Path.of(backupDir));
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss"));
            String safeLabel = label.replaceAll("[^a-zA-Z0-9\\-_.]", "-");
            Path target = Path.of(backupDir).resolve(safeLabel + "-" + timestamp + ".db");
            Files.copy(dbPath, target);
            return target;
        } catch (IOException e) {
            throw new BusinessException("数据库备份失败: " + e.getMessage());
        }
    }

    private Path resolveSqlitePath(String url) {
        if (url == null || !url.startsWith("jdbc:sqlite:")) {
            throw new BusinessException("仅支持 jdbc:sqlite 数据库备份");
        }
        return Path.of(url.substring("jdbc:sqlite:".length())).normalize();
    }
}
