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

export enum PageViewAction {
  VIEW_ANALYSIS_RESULTS = 'VIEW_ANALYSIS_RESULTS',
  VIEW_ANALYSIS_RESULTS_FROM_ORDER = 'VIEW_ANALYSIS_RESULTS_FROM_ORDER',
  REGISTRATION_SUCCESS = 'REGISTRATION_SUCCESS',
  VIEW_ORDER_ANALYSIS = 'VIEW_ORDER_ANALYSIS',
  VIEW_TEAM_ACCOUNT_DASHBOARD = 'VIEW_TEAM_ACCOUNT_DASHBOARD',
  VIEW_TTO_SERVICE_BOOKING = 'VIEW_TTO_SERVICE_BOOKING',
}

export const createPageViewLog = async ({
  accountId,
  action,
  extraData,
}: {
  accountId: string;
  action: PageViewAction;
  extraData?: Record<string, any>;
}) => {
  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;
    }

    await supabase
      .schema('audit')
      .from('page_views')
      .insert({
        account_id: accountId,
        action,
        changed_by: user.id,
        extra_data: extraData,
      })
      .throwOnError();
  } catch (error) {
    console.error('Failed to insert page view log', error);
  }
};
