package ru.otus.mobile.db;

import com.google.inject.Inject;

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

public final class DbClient {
    private final DbConfig config;

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

    public void clearWishlistsByUsername(String username) {
        executeUpdate("""
                DELETE FROM wishlists
                WHERE user_id IN (SELECT id FROM users WHERE username = ?)
                """, username, "clear wishlists");
    }

    public void clearGiftsByUsername(String username) {
        executeUpdate("""
                DELETE FROM gifts
                WHERE wish_id IN (
                    SELECT w.id
                    FROM wishlists w
                    JOIN users u ON u.id = w.user_id
                    WHERE u.username = ?
                )
                """, username, "clear gifts");
    }

    public void clearReservationByUsername(String username) {
        executeUpdate("""
                UPDATE gifts
                SET is_reserved = false
                WHERE wish_id IN (
                    SELECT w.id
                    FROM wishlists w
                    JOIN users u ON u.id = w.user_id
                    WHERE u.username = ?
                )
                """, username, "reset reservation status");
    }

    public void doNothing(String username) {
        // no-op preparation for accounts that do not require DB setup
    }

    private void executeUpdate(String sql, String username, String operation) {
        try (Connection connection = DriverManager.getConnection(config.url(), config.user(), config.password())) {
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, username);
                statement.executeUpdate();
            }
        } catch (SQLException e) {
            throw new IllegalStateException("Failed to " + operation + " for username " + username, e);
        }
    }
}
