package com.bitnix.dirtguilds.data;

import com.bitnix.dirtguilds.DirtGuildsPlugin;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class DatabaseManager {

    private final DirtGuildsPlugin plugin;
    private HikariDataSource dataSource;

    public DatabaseManager(DirtGuildsPlugin plugin) {
        this.plugin = plugin;
    }

    public void initialize() {
        String type = plugin.getConfig().getString("database.type", "SQLITE").toUpperCase();

        HikariConfig config = new HikariConfig();

        if (type.equals("MYSQL")) {
            String host = plugin.getConfig().getString("database.mysql.host");
            int port = plugin.getConfig().getInt("database.mysql.port");
            String database = plugin.getConfig().getString("database.mysql.database");
            String username = plugin.getConfig().getString("database.mysql.username");
            String password = plugin.getConfig().getString("database.mysql.password");
            String properties = plugin.getConfig().getString("database.mysql.properties", "");

            config.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + database + properties);
            config.setUsername(username);
            config.setPassword(password);
            config.setMaximumPoolSize(10);
        } else {
            String fileName = plugin.getConfig().getString("database.sqlite.file", "guilds.db");
            File dbFile = new File(plugin.getDataFolder(), fileName);

            if (!plugin.getDataFolder().exists()) {
                plugin.getDataFolder().mkdirs();
            }

            config.setJdbcUrl("jdbc:sqlite:" + dbFile.getAbsolutePath());
            config.setMaximumPoolSize(1);
        }

        config.setPoolName("DirtGuildsPool");
        this.dataSource = new HikariDataSource(config);

        createTables();
    }

    private void createTables() {
        try (Connection connection = getConnection(); Statement statement = connection.createStatement()) {
            statement.executeUpdate("""
                CREATE TABLE IF NOT EXISTS guilds (
                    id VARCHAR(36) PRIMARY KEY,
                    name VARCHAR(32) NOT NULL UNIQUE,
                    prefix VARCHAR(64) NOT NULL,
                    owner VARCHAR(36) NOT NULL,
                    level INT NOT NULL,
                    bank_balance DOUBLE NOT NULL,
                    friendly_fire BOOLEAN NOT NULL
                )
                """);

            statement.executeUpdate("""
                CREATE TABLE IF NOT EXISTS guild_members (
                    guild_id VARCHAR(36) NOT NULL,
                    player_uuid VARCHAR(36) NOT NULL,
                    rank_name VARCHAR(32) NOT NULL,
                    PRIMARY KEY (guild_id, player_uuid)
                )
                """);

            statement.executeUpdate("""
                CREATE TABLE IF NOT EXISTS guild_vault_items (
                    guild_id VARCHAR(36) NOT NULL,
                    slot_index INT NOT NULL,
                    item_data TEXT NOT NULL,
                    PRIMARY KEY (guild_id, slot_index)
                )
                """);
        } catch (SQLException exception) {
            throw new RuntimeException("Failed to create database tables", exception);
        }
    }

    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public void close() {
        if (dataSource != null && !dataSource.isClosed()) {
            dataSource.close();
        }
    }
}
