#include <AK/String.h>
#include <AK/Variant.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Iterator.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/IDBCursor.h>
#include <LibWeb/Bindings/IDBObjectStore.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/HTML/DOMStringList.h>
#include <LibWeb/IndexedDB/IDBIndex.h>
#include <LibWeb/IndexedDB/IDBObjectStore.h>
#include <LibWeb/IndexedDB/IDBRequest.h>
#include <LibWeb/IndexedDB/IDBTransaction.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

void IDBObjectStoreConstructor::initialize(JS::Realm& realm, JS::NativeFunction& object)
{
    auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;

    
    object.define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "IDBObjectStore"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<IDBObjectStorePrototype>(realm, "IDBObjectStore"_fly_string), 0);
}

JS::ThrowCompletionOr<GC::Ref<JS::Object>> IDBObjectStoreConstructor::construct([[maybe_unused]] InterfaceConstructor& constructor, [[maybe_unused]] JS::FunctionObject& new_target)
{
    WebIDL::log_trace(constructor.vm(), "IDBObjectStoreConstructor::construct");
    return constructor.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAConstructor, "IDBObjectStore");
}

void IDBObjectStorePrototype::initialize(JS::Realm& realm, JS::Object& object)
{
    [[maybe_unused]] auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable;

    object.set_prototype(realm.intrinsics().object_prototype());

    auto name_id = "name"_utf16_fly_string;
    auto native_name_getter = JS::NativeFunction::create(realm, name_getter, 0, name_id, &realm, "get"sv);
    auto native_name_setter = JS::NativeFunction::create(realm, name_setter, 1, name_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto name_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(name_id, native_name_getter, native_name_setter, name_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto key_path_id = "keyPath"_utf16_fly_string;
    auto native_key_path_getter = JS::NativeFunction::create(realm, key_path_getter, 0, key_path_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_key_path_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto key_path_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(key_path_id, native_key_path_getter, native_key_path_setter, key_path_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto index_names_id = "indexNames"_utf16_fly_string;
    auto native_index_names_getter = JS::NativeFunction::create(realm, index_names_getter, 0, index_names_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_index_names_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto index_names_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(index_names_id, native_index_names_getter, native_index_names_setter, index_names_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto transaction_id = "transaction"_utf16_fly_string;
    auto native_transaction_getter = JS::NativeFunction::create(realm, transaction_getter, 0, transaction_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_transaction_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto transaction_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(transaction_id, native_transaction_getter, native_transaction_setter, transaction_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto auto_increment_id = "autoIncrement"_utf16_fly_string;
    auto native_auto_increment_getter = JS::NativeFunction::create(realm, auto_increment_getter, 0, auto_increment_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_auto_increment_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto auto_increment_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(auto_increment_id, native_auto_increment_getter, native_auto_increment_setter, auto_increment_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    object.define_native_function(realm, "put"_utf16_fly_string, put, 1, default_attributes);

    object.define_native_function(realm, "add"_utf16_fly_string, add, 1, default_attributes);

    object.define_native_function(realm, "delete"_utf16_fly_string, delete_, 1, default_attributes);

    object.define_native_function(realm, "clear"_utf16_fly_string, clear, 0, default_attributes);

    object.define_native_function(realm, "get"_utf16_fly_string, get, 1, default_attributes);

    object.define_native_function(realm, "getKey"_utf16_fly_string, get_key, 1, default_attributes);

    object.define_native_function(realm, "getAll"_utf16_fly_string, get_all, 0, default_attributes);

    object.define_native_function(realm, "getAllKeys"_utf16_fly_string, get_all_keys, 0, default_attributes);

    object.define_native_function(realm, "getAllRecords"_utf16_fly_string, get_all_records, 0, default_attributes);

    object.define_native_function(realm, "count"_utf16_fly_string, count, 0, default_attributes);

    object.define_native_function(realm, "openCursor"_utf16_fly_string, open_cursor, 0, default_attributes);

    object.define_native_function(realm, "openKeyCursor"_utf16_fly_string, open_key_cursor, 0, default_attributes);

    object.define_native_function(realm, "index"_utf16_fly_string, index, 1, default_attributes);

    object.define_native_function(realm, "createIndex"_utf16_fly_string, create_index, 2, default_attributes);

    object.define_native_function(realm, "deleteIndex"_utf16_fly_string, delete_index, 1, default_attributes);

    object.define_direct_property(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "IDBObjectStore"_utf16), JS::Attribute::Configurable);
}

void IDBObjectStorePrototype::define_unforgeable_attributes(JS::Realm& realm, [[maybe_unused]] JS::Object& object)
{
    [[maybe_unused]] auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
}

[[maybe_unused]] static JS::ThrowCompletionOr<IndexedDB::IDBObjectStore*> impl_from(JS::VM& vm, JS::Value js_value)
{

    if (auto impl = js_value.as_if<IndexedDB::IDBObjectStore>())
        return impl.ptr();
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "IDBObjectStore");
}

[[maybe_unused]] static JS::ThrowCompletionOr<IndexedDB::IDBObjectStore*> impl_from(JS::VM& vm)
{
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &vm.current_realm()->global_object();
    return impl_from(vm, this_value);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::name_getter)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::name_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->name(); }));

    return WebIDL::primitive_string_from_string(vm, R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::key_path_getter)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::key_path_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->key_path(); }));

    return R;
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::index_names_getter)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::index_names_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->index_names(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::transaction_getter)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::transaction_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->transaction(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::auto_increment_getter)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::auto_increment_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->auto_increment(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::name_setter)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::name_setter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    // 1. Let V be undefined.
    auto V = JS::js_undefined();

    // 2. If any arguments were passed, then set V to the value of the first argument passed.
    if (vm.argument_count() > 0)
        V = vm.argument(0);

    // 3. Let id be attribute’s identifier.

    // 4. Let idlObject be null.
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = nullptr;

    // 5. If attribute is a regular attribute:

    // 1. Let jsValue be the this value, if it is not null or undefined, or realm’s global object otherwise. (This will subsequently cause a TypeError in a few steps, if the global object does not implement target and [LegacyLenientThis] is not specified.)
    auto js_value = vm.this_value();
    if (js_value.is_nullish())
        js_value = &realm.global_object();

    // 2. FIXME: If jsValue is a platform object, then perform a security check, passing jsValue, attribute’s identifier, and "setter".

    // 3. Let validThis be true if jsValue implements target, or false otherwise.
    auto maybe_idl_object = impl_from(vm, js_value);

    // 4. If validThis is false and attribute was not specified with the [LegacyLenientThis] extended attribute, then throw a TypeError.
    idl_object = TRY(maybe_idl_object);

    auto original_steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {
        // 6. Let idlValue be determined as follows:
        // -> Otherwise, idlValue is the result of converting V to an IDL value of attribute’s type.
        auto idl_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, V));
    }(); }));

        // 7. Run the setter steps of attribute with idlObject as this and idlValue as the value.
        auto setter_result = [&]() -> JS::ThrowCompletionOr<void> {
            TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_name(idl_value); }));
    return {};
        }();

        if (setter_result.is_error())
            return setter_result.release_error();

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY(original_steps());
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::put)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::put");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "put");

    auto arg0 = vm.argument(0);
    auto value = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    auto arg1 = vm.argument(1);
    Optional<JS::Value> key {};
    if (!arg1.is_undefined())
        key = TRY(throw_dom_exception_if_needed(vm, [&] { return arg1; }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->put(value, key); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::add)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::add");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "add");

    auto arg0 = vm.argument(0);
    auto value = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    auto arg1 = vm.argument(1);
    Optional<JS::Value> key {};
    if (!arg1.is_undefined())
        key = TRY(throw_dom_exception_if_needed(vm, [&] { return arg1; }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->add(value, key); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::delete_)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::delete_");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "delete");

    auto arg0 = vm.argument(0);
    auto query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->delete_(query); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::clear)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::clear");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->clear(); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::get)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::get");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "get");

    auto arg0 = vm.argument(0);
    auto query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get(query); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::get_key)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::get_key");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "getKey");

    auto arg0 = vm.argument(0);
    auto query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_key(query); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::get_all)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::get_all");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    Optional<JS::Value> query {};
    if (!arg0.is_undefined())
        query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    auto arg1 = vm.argument(1);
    Optional<WebIDL::UnsignedLong> count {};
    if (!arg1.is_undefined())
        count = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg1, WebIDL::EnforceRange::Yes, WebIDL::Clamp::No); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_all(query, count); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::get_all_keys)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::get_all_keys");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    Optional<JS::Value> query {};
    if (!arg0.is_undefined())
        query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    auto arg1 = vm.argument(1);
    Optional<WebIDL::UnsignedLong> count {};
    if (!arg1.is_undefined())
        count = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg1, WebIDL::EnforceRange::Yes, WebIDL::Clamp::No); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_all_keys(query, count); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::get_all_records)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::get_all_records");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    IDBGetAllOptions options = IDBGetAllOptions {};
    if (!arg0.is_undefined())
        options = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_idb_get_all_options(vm, arg0); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_all_records(options); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::count)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::count");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    Optional<JS::Value> query {};
    if (!arg0.is_undefined())
        query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->count(query); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::open_cursor)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::open_cursor");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    Optional<JS::Value> query {};
    if (!arg0.is_undefined())
        query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    auto arg1 = vm.argument(1);
    IDBCursorDirection direction = IDBCursorDirection::Next;
    if (!arg1.is_undefined())
        direction = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_idb_cursor_direction(vm, arg1); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->open_cursor(query, direction); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::open_key_cursor)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::open_key_cursor");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    Optional<JS::Value> query {};
    if (!arg0.is_undefined())
        query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    auto arg1 = vm.argument(1);
    IDBCursorDirection direction = IDBCursorDirection::Next;
    if (!arg1.is_undefined())
        direction = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_idb_cursor_direction(vm, arg1); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->open_key_cursor(query, direction); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::index)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::index");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "index");

    auto arg0 = vm.argument(0);
    auto name = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg0));
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->index(name); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::create_index)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::create_index");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "createIndex", "2");

    auto arg0 = vm.argument(0);
    auto name = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg0));
    }(); }));

    auto arg1 = vm.argument(1);
    auto key_path = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Variant<String, Vector<String>>> {

        if (arg1.is_object()) {
            [[maybe_unused]] auto& object = arg1.as_object();

            // 1. Let method be ? GetMethod(V, @@iterator).
            auto method = TRY(arg1.get_method(vm, vm.well_known_symbol_iterator()));

            // 2. If method is not undefined, return the result of creating a sequence of that type from V and method.
            if (method) {
                auto sequence_union_type = TRY([&]() -> JS::ThrowCompletionOr<Vector<String>> {
        // To create an IDL value of type sequence<T> given an iterable iterable and an iterator getter method, perform the following steps:
        // 1. Let iteratorRecord be ? GetIteratorFromMethod(iterable, method).
        auto iterator = TRY(JS::get_iterator_from_method(vm, arg1, *method));

        Vector<String> sequence;

        // 2. Initialize i to be 0.
        // 3. Repeat
        for (;;) {
            // 1. Let next be ? IteratorStepValue(iteratorRecord).
            auto next = TRY(JS::iterator_step_value(vm, iterator));

            // 2. If next is done, then return an IDL sequence value of type sequence<T> of length i, where the value of the element at index j is Sj.
            if (!next.has_value())
                break;

            // 3. Initialize Si to the result of converting next to an IDL value of type T.
            auto next_value = next.release_value();
            auto sequence_item = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, next_value));
    }(); }));

            // 4. Set i to i + 1.
            sequence.append(sequence_item);
        }

        return sequence;
    }());
                return Variant<String, Vector<String>> { sequence_union_type };
            }

        }

        auto keyPath_string = TRY([&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg1));
    }());
        return Variant<String, Vector<String>> { keyPath_string };

        return vm.throw_completion<JS::TypeError>("No union types matched"_utf16);
    }(); }));

    auto arg2 = vm.argument(2);
    IDBIndexParameters options = IDBIndexParameters {};
    if (!arg2.is_undefined())
        options = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_idb_index_parameters(vm, arg2); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->create_index(name, key_path, options); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBObjectStorePrototype::delete_index)
{
    WebIDL::log_trace(vm, "IDBObjectStorePrototype::delete_index");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBObjectStore* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "deleteIndex");

    auto arg0 = vm.argument(0);
    auto name = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg0));
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->delete_index(name); }));
    return JS::js_undefined();
}

// https://webidl.spec.whatwg.org/#es-dictionary
JS::ThrowCompletionOr<IDBIndexParameters> convert_to_idl_value_for_idb_index_parameters(JS::VM& vm, JS::Value js_dict)
{
    // 1. If jsDict is not an Object and jsDict is neither undefined nor null, then throw a TypeError.
    if (!js_dict.is_object() && !js_dict.is_nullish())
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "IDBIndexParameters");

    // 2. Let idlDict be an empty ordered map, representing a dictionary of type D.
    // 3. Let dictionaries be a list consisting of D and all of D’s inherited dictionaries, in order from least to most derived.
    // 4. For each dictionary dictionary in dictionaries, in order:
    // NB: We defer construction until the return initializer because some members may not be default-constructible. Inherited dictionaries are represented by the generated C++ struct inheritance.

    // 5. Return idlDict.
    return IDBIndexParameters {
        .multi_entry = TRY([&]() -> JS::ThrowCompletionOr<bool> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("multiEntry"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value.to_boolean(); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = false;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        .unique = TRY([&]() -> JS::ThrowCompletionOr<bool> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("unique"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value.to_boolean(); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = false;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
    };
}

// https://webidl.spec.whatwg.org/#es-dictionary
JS::ThrowCompletionOr<IDBGetAllOptions> convert_to_idl_value_for_idb_get_all_options(JS::VM& vm, JS::Value js_dict)
{
    // 1. If jsDict is not an Object and jsDict is neither undefined nor null, then throw a TypeError.
    if (!js_dict.is_object() && !js_dict.is_nullish())
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "IDBGetAllOptions");

    // 2. Let idlDict be an empty ordered map, representing a dictionary of type D.
    // 3. Let dictionaries be a list consisting of D and all of D’s inherited dictionaries, in order from least to most derived.
    // 4. For each dictionary dictionary in dictionaries, in order:
    // NB: We defer construction until the return initializer because some members may not be default-constructible. Inherited dictionaries are represented by the generated C++ struct inheritance.

    // 5. Return idlDict.
    return IDBGetAllOptions {
        .count = TRY([&]() -> JS::ThrowCompletionOr<Optional<WebIDL::UnsignedLong>> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("count"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, js_member_value, WebIDL::EnforceRange::Yes, WebIDL::Clamp::No); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 7. Otherwise, jsMemberValue is undefined and the member is optional.
            return OptionalNone {};
        }()),
        .direction = TRY([&]() -> JS::ThrowCompletionOr<IDBCursorDirection> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("direction"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_idb_cursor_direction(vm, js_member_value); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = IDBCursorDirection::Next;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        .query = TRY([&]() -> JS::ThrowCompletionOr<JS::Value> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("query"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value; }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = JS::js_null();

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
    };
}

} // namespace Web::Bindings
