package ru.otus.mobile.db;

import com.google.inject.Inject;
import ru.otus.mobile.config.MobileConfig;
import ru.otus.mobile.config.TestAccount;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public final class DbClient {
    private final DbConfig config;
    private final MobileConfig mobileConfig;

    @Inject
    public DbClient(DbConfig config, MobileConfig mobileConfig) {
        this.config = config;
        this.mobileConfig = mobileConfig;
    }

    public void resetData(TestAccount account) {
        try (Connection connection = DriverManager.getConnection(config.url(), config.user(), config.password());
             PreparedStatement statement = connection.prepareStatement(account.resetSql())) {
            if (account == TestAccount.RESERVATION) {
                statement.setString(1, mobileConfig.reservationOwnerUsername());
                statement.setString(2, account.username());
            } else {
                statement.setString(1, account.username());
            }
            statement.execute();
        } catch (SQLException e) {
            throw new IllegalStateException("Failed to prepare test data for account " + account.name(), e);
        }
    }
}
