import React, { useState, useContext, createContext } from "react";

interface AuthState {
  loggedIn: boolean;
  login: (password: string) => Promise<boolean>;
  logout: () => void;
  headers?: HeadersInit;
}

const AuthContext = createContext<AuthState>({
  loggedIn: false,
  login: () => Promise.resolve(false),
  logout: () => console.error("No parent AuthContext found!"),
});

export const AuthProvider: React.FC = ({ children }) => {
  const [headers, setHeaders] = useState<HeadersInit | undefined>();

  const logout = () => setHeaders(undefined);

  const login = async (password: string): Promise<boolean> => {
    const username = process.env.NEXT_PUBLIC_EDITOR_USERNAME;

    if (!username) {
      throw new Error(
        "Missing NEXT_PUBLIC_EDITOR_USERNAME environment variable"
      );
    }

    const newHeaders = {
      Authorization: `CustomBasic ${btoa(`${username}:${password}`)}`,
    };

    const res = await fetch("/api/editor/links", { headers: newHeaders });

    if (res.status === 200) {
      setHeaders(newHeaders);
      return true;
    } else {
      logout();
      return false;
    }
  };

  return (
    <AuthContext.Provider
      value={{ loggedIn: !!headers, login, logout, headers }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export function useAuth(): AuthState {
  return useContext(AuthContext);
}
