'use server';

import { RequestStatus, SyncStatus } from '@/lib/types/audit';
import { ConnectedOnlineMethodName } from '@/lib/types/connected-online';
import { ExternalApi } from '@/lib/types/external';
import { MedipostAction } from '@/lib/types/medipost';
import { getSupabaseServerAdminClient } from '@/packages/supabase/src/clients/server-admin-client';

export default async function logRequestResult(
  requestApi: keyof typeof ExternalApi,
  requestApiMethod: `${ConnectedOnlineMethodName}` | `${MedipostAction}`,
  status: RequestStatus,
  comment?: string,
  startTime?: string,
  serviceId?: number,
  serviceProviderId?: number,
) {
  const { error } = await getSupabaseServerAdminClient()
    .schema('audit')
    .from('request_entries')
    .insert({
      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);
  }
}

export async function logMedipostDispatch({
  medusaOrderId,
  isSuccess,
  isMedipostError,
  errorMessage,
}: {
  medusaOrderId: string;
  isSuccess: boolean;
  isMedipostError: boolean;
  errorMessage?: string;
}) {
  const { error } = await getSupabaseServerAdminClient()
    .schema('audit')
    .from('medipost_dispatch')
    .insert({
      medusa_order_id: medusaOrderId,
      is_success: isSuccess,
      is_medipost_error: isMedipostError,
      error_message: errorMessage,
    });

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

export async function getMedipostDispatchTries(medusaOrderId: string) {
  const { data } = await getSupabaseServerAdminClient()
    .schema('medreport')
    .rpc('get_medipost_dispatch_tries', { p_medusa_order_id: medusaOrderId })
    .throwOnError();

  return data;
}

export async function logSyncResult({
  operation,
  comment,
  status,
  changed_by_role,
}: {
  operation: string;
  comment?: string;
  status: SyncStatus;
  changed_by_role: string;
}) {
  const { error } = await getSupabaseServerAdminClient()
    .schema('audit')
    .from('sync_entries')
    .insert({
      operation,
      comment,
      status,
      changed_by_role,
    });

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