import { useEffect, type FC } from "react";
import { createBrowserRouter, RouterProvider } from "react-router-dom";

import IndexPage from "./pages/Index";
import LoginPage from "./pages/Login";
import RegisterPage from "./pages/Register";
import { useDbContext } from "./context/db/db";
import { openDB } from "idb";
import AgreementPage from "./pages/Agreement";

const router = createBrowserRouter([
  {
    path: "/",
    element: <IndexPage />,
  },
  {
    path: "/agreement",
    element: <AgreementPage />,
  },
  {
    path: "/login",
    element: <LoginPage />,
  },
  {
    path: "/register",
    element: <RegisterPage />,
  },
]);

const App: FC = () => {
  const { db, setDb } = useDbContext();

  useEffect(() => {
    const openConnection = async () => {
      const dbPromise = openDB("guard-local", 3, {
        upgrade: (db) => {
          if (!db.objectStoreNames.contains("accounts")) {
            db.createObjectStore("accounts", { keyPath: "accountId" });
          }
        },
      });

      const conn = await dbPromise;

      setDb(conn);
    };

    openConnection();
  }, [db, setDb]);

  return <RouterProvider router={router} />;
};

export default App;
