-- =============================================================================
-- MC Cars - Public lead creation RPC
-- Allows anon/authenticated callers to create leads and receive the inserted id
-- without granting SELECT on public.leads.
-- =============================================================================

create or replace function public.create_lead(
    p_name text,
    p_email text,
    p_phone text default '',
    p_vehicle_id uuid default null,
    p_vehicle_label text default '',
    p_date_from date default null,
    p_date_to date default null,
    p_message text default '',
    p_source text default 'website'
)
returns uuid
language plpgsql
security definer
set search_path = public
as $$
declare
    v_id uuid;
begin
    insert into public.leads (
        name,
        email,
        phone,
        vehicle_id,
        vehicle_label,
        date_from,
        date_to,
        message,
        source
    )
    values (
        p_name,
        p_email,
        coalesce(p_phone, ''),
        p_vehicle_id,
        coalesce(p_vehicle_label, ''),
        p_date_from,
        p_date_to,
        coalesce(p_message, ''),
        coalesce(p_source, 'website')
    )
    returning id into v_id;

    return v_id;
end;
$$;

revoke all on function public.create_lead(text, text, text, uuid, text, date, date, text, text) from public;
grant execute on function public.create_lead(text, text, text, uuid, text, date, date, text, text) to anon, authenticated, service_role;

notify pgrst, 'reload schema';
