import { codeApi } from "@/api/code";
import { create } from "zustand";

export interface OAuthState {
  active: boolean;
  clientID: string;
  redirectURI: string;
  scope: string[];
  state: string;
  nonce: string;

  parseSearchParams: (params: URLSearchParams) => void;
  selectSession: (token: string) => Promise<void>;
}

export const useOAuth = create<OAuthState>((set, get) => ({
  active: false,
  clientID: "",
  redirectURI: "",
  scope: [],
  state: "",
  nonce: "",

  parseSearchParams: (params) => {
    if (get().active) return;

    set({
      active: true,
      clientID: params.get("client_id") ?? "",
      redirectURI: params.get("redirect_uri") ?? "",
      scope: (params.get("scope") ?? "")
        .trim()
        .split(" ")
        .filter((s) => s.length > 0),
      state: params.get("state") ?? "",
      nonce: params.get("nonce") ?? "",
    });
  },

  selectSession: async (token) => {
    const { active, redirectURI, nonce, state } = get();
    if (active && redirectURI) {
      const codeResponse = await codeApi(token, nonce);

      const params = new URLSearchParams({
        code: codeResponse.code,
        state,
      });

      window.location.replace(`${redirectURI}?${params.toString()}`);
    }
  },
}));
