import { useQueryClient } from '@tanstack/react-query';
import { useClient } from 'hooks/useClient';
import { startRegistration, startAuthentication } from '@simplewebauthn/browser';
import type {
  PublicKeyCredentialCreationOptionsJSON,
  PublicKeyCredentialRequestOptionsJSON,
} from '@simplewebauthn/browser';

type PasskeyUser = {
  id: number;
  email: string | null;
  firstName?: string | null;
  lastName?: string | null;
};

export const usePasskeys = () => {
  const queryClient = useQueryClient();
  const authClient = useClient('/api/auth');

  const createPasskeyCredentials = async (user: PasskeyUser) => {
    // Get registration options from server
    const options = (await authClient.post(
      `/passkeys/challenge/${user.email}`,
    )) as PublicKeyCredentialCreationOptionsJSON;

    // Create passkey using browser API (handled by SimpleWebAuthn)
    const registrationResponse = await startRegistration({ optionsJSON: options });

    // Send full response to server for verification
    await authClient.post(`/passkeys/credentials`, registrationResponse);
    queryClient.invalidateQueries({ queryKey: ['CURRENT_USER'] });
  };

  const signinWithPasskey = async (user: PasskeyUser) => {
    // Get authentication options from server
    const options = (await authClient.get(`/passkeys/signin/${user.email}`)) as PublicKeyCredentialRequestOptionsJSON;

    // Authenticate using browser API (handled by SimpleWebAuthn)
    const authenticationResponse = await startAuthentication({ optionsJSON: options });

    // Send full response to server for verification
    const url = `/passkeys/verify/${user.email}`;
    const data = (await authClient.post(url, authenticationResponse)) as { token: string };
    localStorage.setItem('BEARER_TOKEN', data.token);
    queryClient.invalidateQueries({ queryKey: ['CURRENT_USER'] });
    return data;
  };

  const authorizeWithPasskey = async (user: PasskeyUser) => {
    // Get authentication options from server
    const options = (await authClient.get(`/passkeys/signin/${user.email}`)) as PublicKeyCredentialRequestOptionsJSON;

    // Authenticate using browser API (handled by SimpleWebAuthn)
    const authenticationResponse = await startAuthentication({ optionsJSON: options });

    // Return the credential ID for authorization purposes
    return authenticationResponse.id;
  };

  return { createPasskeyCredentials, signinWithPasskey, authorizeWithPasskey };
};
