/*
 Copyright 2019 Florian Dold

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 or implied. See the License for the specific language governing
 permissions and limitations under the License.
 */

import test from "ava";
import * as fs from "node:fs";
import { createSqliteBackend } from "./SqliteBackend.js";
import { ResultLevel, StoreLevel } from "./backend-interface.js";
import { BridgeIDBKeyRange } from "./bridge-idb.js";
import { createNodeHelperSqlite3Impl } from "./node-helper-sqlite3-impl.js";

test("sqlite3 backend", async (t) => {
  const filename = "mytestdb.sqlite3";
  try {
    fs.unlinkSync(filename);
  } catch (e) {
    // Do nothing.
  }
  try {
    const sqlite3Impl = await createNodeHelperSqlite3Impl();
    const backend = await createSqliteBackend(sqlite3Impl, {
      filename,
    });
    const dbConnRes = await backend.connectDatabase("mydb");
    const dbConn = dbConnRes.conn;
    const tx = await backend.enterVersionChange(dbConn, 1);
    backend.createObjectStore(tx, "books", "isbn", true);
    backend.createIndex(tx, "byName", "books", "name", false, false);
    await backend.storeRecord(tx, {
      objectStoreName: "books",
      storeLevel: StoreLevel.AllowOverwrite,
      value: { name: "foo" },
      key: undefined,
    });
    const res = await backend.getObjectStoreRecords(tx, {
      direction: "next",
      limit: 1,
      objectStoreName: "books",
      resultLevel: ResultLevel.Full,
      range: BridgeIDBKeyRange.only(1),
    });
    t.deepEqual(res.count, 1);
    t.deepEqual(res.primaryKeys![0], 1);
    t.deepEqual(res.values![0].name, "foo");

    const indexRes = await backend.getIndexRecords(tx, {
      direction: "next",
      limit: 1,
      objectStoreName: "books",
      indexName: "byName",
      resultLevel: ResultLevel.Full,
      range: BridgeIDBKeyRange.only("foo"),
    });

    t.deepEqual(indexRes.count, 1);
    t.deepEqual(indexRes.values![0].isbn, 1);
    t.deepEqual(indexRes.values![0].name, "foo");

    await backend.commit(tx);

    const tx2 = await backend.beginTransaction(dbConn, ["books"], "readwrite");
    await backend.commit(tx2);

    await backend.close(dbConn);

    t.pass();
  } catch (e: any) {
    console.log(e);
    throw e;
  }
});
