begin;
-- Test registration now skips the SMS step. Keep the trusted app-metadata gate
-- and existing per-user event keys; do not rewrite historical notifications.
create or replace function marketplace_private.registration_notify(p_user uuid)
returns void language plpgsql security definer set search_path='' as $$
declare p marketplace_private.customer_profiles;sandbox boolean;
begin
 select * into p from marketplace_private.customer_profiles where user_id=p_user;
 if p.user_id is null then return;end if;
 select coalesce(raw_app_meta_data->>'phone_verification_mode'='sandbox',false) into sandbox from auth.users where id=p_user;
 insert into marketplace_private.admin_notifications(event_key,event_type,user_id,title,body,action_url)
 values('registration:'||p.user_id,'customer_registered',p.user_id,'{"fa":"ثبت‌نام کاربر جدید"}',jsonb_build_object('fa',coalesce(nullif(trim(p.first_name||' '||p.last_name),''),p.username)||' ثبت‌نام کرده است. پس از ارسال مدارک، درخواست احراز هویت برای بررسی نمایش داده می‌شود.'||case when sandbox then ' ثبت‌نام در حالت آزمایشی و بدون ارسال پیامک انجام شده و به معنی تأیید مالکیت شماره یا احراز هویت نیست.' else '' end),'/?section=notifications') on conflict(event_key) do nothing;
 perform marketplace_private.customer_notify(p.user_id,'registration:'||p.user_id,'به پلانک خوش آمدید','ثبت‌نام شما تکمیل شد. برای تکمیل حساب، اطلاعات و مدارک احراز هویت خود را ارسال کنید.','success');
end$$;
revoke all on function marketplace_private.registration_notify(uuid) from public,anon,authenticated;
commit;
