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";
import { openDB } from "idb";
import AgreementPage from "./pages/Agreement";
import OAuthAuthorizePage from "./pages/OAuthAuthorize";

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

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;
