package com.reg.server.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.sqlite.SQLiteDataSource;

import javax.sql.DataSource;
import java.io.File;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Configuration
public class DatabaseConfig {

	@Bean
	public DataSource dataSource() {
		Path baseDir = resolveBaseDir();
		Path dataDir = baseDir.resolve("data");
		Path dbFile = dataDir.resolve("app.db");
		try {
			Files.createDirectories(dataDir);
		} catch (Exception ignored) {
			// rely on SQLite to fail loudly if directory is not writable
		}

		SQLiteDataSource ds = new SQLiteDataSource();
		ds.setUrl("jdbc:sqlite:" + dbFile.toString());
		return ds;
	}

	private Path resolveBaseDir() {
		try {
			// When running from JAR, location points to the JAR file; from IDE, to classes directory.
			java.net.URL location = DatabaseConfig.class.getProtectionDomain()
					.getCodeSource()
					.getLocation();
			String path = location.getPath();
			// Handle JAR path: jar:file:/path/to/app.jar!/BOOT-INF/classes!/
			if (path.contains(".jar")) {
				// Extract the JAR file path
				int jarIndex = path.indexOf(".jar");
				path = path.substring(0, jarIndex + 4);
				// Remove "file:" prefix if present
				if (path.startsWith("file:")) {
					path = path.substring(5);
				}
				// On Windows, remove leading slash before drive letter (e.g., /D:/...)
				if (path.length() > 2 && path.charAt(0) == '/' && path.charAt(2) == ':') {
					path = path.substring(1);
				}
				// Decode URL encoding
				path = java.net.URLDecoder.decode(path, "UTF-8");
				Path jarPath = Paths.get(path);
				Path parent = jarPath.getParent();
				if (parent != null) {
					return parent;
				}
			} else {
				// Running from IDE/classes directory
				Path classesPath = Paths.get(location.toURI());
				Path parent = classesPath.getParent();
				if (parent != null) {
					return parent;
				}
			}
		} catch (Exception ignored) {
			// fall back
		}
		return Paths.get(System.getProperty("user.dir", "."));
	}
}
