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

export const createCartEntriesLog = async ({
  operation,
  accountId,
  cartId,
  variantId,
  comment,
}: {
  operation: string;
  accountId: string;
  cartId: string;
  variantId?: string;
  comment?: string;
}) => {
  try {
    const supabase = getSupabaseServerClient();

    const {
      data: { user },
      error: userError,
    } = await supabase.auth.getUser();

    if (userError || !user) {
      console.error('No authenticated user found; skipping audit insert');
      return;
    }

    return supabase.schema('audit').from('cart_entries').insert({
      operation,
      account_id: accountId,
      cart_id: cartId,
      changed_by: user.id,
      variant_id: variantId,
      comment,
    });
  } catch (error) {
    console.error('Failed to insert doctor page view log', error);
  }
};
