-- 钱包相关存储过程

-- 1. 充值函数
create or replace function recharge_wallet(
  p_user_id uuid, 
  p_amount decimal
)
returns json
language plpgsql
security definer
as $$
declare
  v_new_balance decimal;
  v_wallet_exists boolean;
begin
  if p_amount <= 0 then
    return json_build_object('success', false, 'message', '充值金额必须大于0');
  end if;

  -- 检查并锁定用户钱包行
  select exists(select 1 from ml_user_wallets where user_id = p_user_id for update) into v_wallet_exists;
  
  if not v_wallet_exists then
    -- 如果钱包不存在，创建它
    insert into ml_user_wallets (user_id, balance) values (p_user_id, 0);
  end if;

  -- 更新余额
  update ml_user_wallets 
  set balance = balance + p_amount, updated_at = now()
  where user_id = p_user_id
  returning balance into v_new_balance;

  -- 插入交易记录
  insert into ml_wallet_transactions (user_id, amount, balance_after, type, description)
  values (p_user_id, p_amount, v_new_balance, 'recharge', '账户在线充值');

  return json_build_object('success', true, 'message', '充值成功', 'new_balance', v_new_balance);
exception when others then
  return json_build_object('success', false, 'message', SQLERRM);
end;
$$;

-- 2. 提现函数
create or replace function withdraw_wallet(
  p_user_id uuid, 
  p_amount decimal
)
returns json
language plpgsql
security definer
as $$
declare
  v_current_balance decimal;
  v_new_balance decimal;
begin
  if p_amount <= 0 then
    return json_build_object('success', false, 'message', '提现金额必须大于0');
  end if;

  -- 检查并锁定用户钱包
  select balance into v_current_balance from ml_user_wallets where user_id = p_user_id for update;
  
  if not found then
    return json_build_object('success', false, 'message', '钱包不存在');
  end if;

  if v_current_balance < p_amount then
     return json_build_object('success', false, 'message', '余额不足');
  end if;

  -- 扣除余额
  update ml_user_wallets 
  set balance = balance - p_amount, updated_at = now()
  where user_id = p_user_id
  returning balance into v_new_balance;

  -- 插入交易记录
  insert into ml_wallet_transactions (user_id, amount, balance_after, type, description)
  values (p_user_id, -p_amount, v_new_balance, 'withdraw', '余额提现');

  return json_build_object('success', true, 'message', '提现申请提交成功', 'new_balance', v_new_balance);
exception when others then
  return json_build_object('success', false, 'message', SQLERRM);
end;
$$;
