import { cache } from 'react';

import { requireUserInServerComponent } from '@/lib/server/require-user-in-server-component';

import { createAccountsApi } from '@kit/accounts/api';
import { getSupabaseServerClient } from '@kit/supabase/server-client';

export type UserAccount = Awaited<ReturnType<typeof loadUserAccount>>;

/**
 * @name loadUserAccount
 * @description
 * Load the user account. It's a cached per-request function that fetches the user workspace data.
 * It can be used across the server components to load the user workspace data.
 */
export const loadUserAccount = cache(accountLoader);

export async function loadCurrentUserAccount() {
  const user = await requireUserInServerComponent();
  const userId = user?.id;
  if (!userId) {
    return { account: null, user: null };
  }
  const account = await loadUserAccount(userId);
  return { account, user };
}

async function accountLoader(userId: string) {
  const client = getSupabaseServerClient();
  const api = createAccountsApi(client);

  return api.getPersonalAccountByUserId(userId);
}
