alter table medreport.account_balance_entries add column "is_analysis_order" boolean;
alter table medreport.account_balance_entries add column "is_analysis_package_order" boolean;

drop function if exists medreport.consume_account_balance(uuid, numeric, text, text);

-- Create function to consume balance (for purchases)
create or replace function medreport.consume_account_balance(
    p_account_id uuid,
    p_amount numeric,
    p_description text,
    p_reference_id text default null,
    p_is_analysis_order boolean default false,
    p_is_analysis_package_order boolean default false
)
returns boolean
language plpgsql
security definer
as $$
declare
    current_balance numeric;
    remaining_amount numeric := p_amount;
    entry_record record;
    consumed_amount numeric;
begin
    -- Get current balance
    current_balance := medreport.get_account_balance(p_account_id);
    
    -- Check if sufficient balance
    if current_balance < p_amount then
        return false;
    end if;
    
    -- Record the consumption
    insert into medreport.account_balance_entries (
        account_id,
        amount,
        entry_type,
        description,
        reference_id,
        created_by,
        is_analysis_order,
        is_analysis_package_order
    ) values (
        p_account_id,
        -p_amount,
        'purchase',
        p_description,
        p_reference_id,
        auth.uid(),
        p_is_analysis_order,
        p_is_analysis_package_order
    );
    
    return true;
end;
$$;

-- Grant execute permission
grant execute on function medreport.consume_account_balance(uuid, numeric, text, text, boolean, boolean) to authenticated, service_role;
