 'use server'
 
import { createClient } from '@supabase/supabase-js';

import { RequestStatus } from '@/lib/types/audit';
import { ConnectedOnlineMethodName } from '@/lib/types/connected-online';
import { ExternalApi } from '@/lib/types/external';
import { MedipostAction } from '@/lib/types/medipost';

export default async function logRequestResult(
  /* personalCode: string, */ requestApi: keyof typeof ExternalApi,
  requestApiMethod: `${ConnectedOnlineMethodName}` | `${MedipostAction}`,
  status: RequestStatus,
  comment?: string,
  startTime?: string,
  serviceId?: number,
  serviceProviderId?: number,
) {
  const supabaseServiceUser = createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY!,
    {
      auth: {
        persistSession: false,
        autoRefreshToken: false,
        detectSessionInUrl: false,
      },
    },
  );

  const { error } = await supabaseServiceUser
    .schema('audit')
    .from('request_entries')
    .insert({
      /* personal_code: personalCode, */
      request_api: requestApi,
      request_api_method: requestApiMethod,
      requested_start_date: startTime,
      status,
      service_id: serviceId,
      service_provider_id: serviceProviderId,
      comment,
    });

  if (error) {
    throw new Error('Failed to insert log entry, error: ' + error.message);
  }
}
