package ru.otus.mobile.db;

public final class DbConfig {
    private final String url;
    private final String user;
    private final String password;
    private final String resetSql;

    private static final String DEFAULT_RESET_SQL = """
            WITH target_user AS (
              SELECT id FROM users WHERE username = ?
            ),
            user_insert AS (
              INSERT INTO users (id, email, password, username)
              SELECT gen_random_uuid(), ?, ?, ?
              WHERE NOT EXISTS (SELECT 1 FROM target_user)
              RETURNING id
            ),
            user_ref AS (
              SELECT id FROM target_user
              UNION ALL
              SELECT id FROM user_insert
            ),
            del_gifts AS (
              DELETE FROM gifts
              WHERE wish_id IN (SELECT id FROM wishlists WHERE user_id IN (SELECT id FROM user_ref))
            ),
            del_wishlists AS (
              DELETE FROM wishlists WHERE user_id IN (SELECT id FROM user_ref)
            )
            SELECT 1;
            """;

    private DbConfig(String url, String user, String password, String resetSql) {
        this.url = url;
        this.user = user;
        this.password = password;
        this.resetSql = resetSql;
    }

    public String url() {
        return url;
    }

    public String user() {
        return user;
    }

    public String password() {
        return password;
    }

    public String resetSql() {
        return resetSql;
    }

    public static DbConfig load() {
        String url = propOrEnv("db.url", "DB_URL");
        String user = propOrEnv("db.user", "DB_USER");
        String password = propOrEnv("db.password", "DB_PASSWORD");
        String resetSql = propOrEnv("db.reset.sql", "DB_RESET_SQL");

        if (isBlank(url) || isBlank(user) || isBlank(password)) {
            throw new IllegalStateException(
                    "DB config is missing. Provide db.url/db.user/db.password or DB_URL/DB_USER/DB_PASSWORD."
            );
        }
        if (isBlank(resetSql)) {
            resetSql = DEFAULT_RESET_SQL;
        }
        return new DbConfig(url, user, password, resetSql);
    }

    private static String propOrEnv(String prop, String env) {
        String value = System.getProperty(prop);
        if (!isBlank(value)) {
            return value;
        }
        return System.getenv(env);
    }

    private static boolean isBlank(String value) {
        return value == null || value.trim().isEmpty();
    }
}
