-- Fix admin_adjust_credits function to use provider_id instead of wallet_id
CREATE OR REPLACE FUNCTION public.admin_adjust_credits(
  p_provider_id UUID, 
  p_amount INTEGER, 
  p_reason TEXT, 
  p_admin_id UUID
)
RETURNS JSON
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
DECLARE
  v_wallet_id UUID;
  v_new_balance INTEGER;
  v_transaction_id UUID;
BEGIN
  -- Verify admin role
  IF NOT EXISTS (SELECT 1 FROM profiles WHERE id = p_admin_id AND role = 'admin') THEN
    RAISE EXCEPTION 'Unauthorized: Admin access required';
  END IF;

  -- Get wallet
  SELECT id, credit_balance INTO v_wallet_id, v_new_balance
  FROM provider_wallets
  WHERE provider_id = p_provider_id
  FOR UPDATE;

  IF v_wallet_id IS NULL THEN
    RAISE EXCEPTION 'Provider wallet not found';
  END IF;

  -- Calculate new balance
  v_new_balance := v_new_balance + p_amount;

  IF v_new_balance < 0 THEN
    RAISE EXCEPTION 'Insufficient balance for deduction';
  END IF;

  -- Update wallet
  UPDATE provider_wallets
  SET 
    credit_balance = v_new_balance,
    updated_at = NOW()
  WHERE id = v_wallet_id;

  -- Record transaction (using provider_id instead of wallet_id)
  INSERT INTO credit_transactions (
    provider_id,
    transaction_type,
    amount,
    description,
    balance_after
  ) VALUES (
    p_provider_id,
    CASE WHEN p_amount > 0 THEN 'admin_credit' ELSE 'admin_debit' END,
    ABS(p_amount),
    p_reason || ' (Admin: ' || p_admin_id::TEXT || ')',
    v_new_balance
  ) RETURNING id INTO v_transaction_id;

  RETURN json_build_object(
    'success', true,
    'new_balance', v_new_balance,
    'transaction_id', v_transaction_id
  );
END;
$$;