-- Informational reports only: a submitted transfer claim is not bank settlement.
begin;
alter table marketplace_private.admin_notifications drop constraint if exists admin_notifications_event_type_check;
alter table marketplace_private.admin_notifications add constraint admin_notifications_event_type_check
 check(event_type in('customer_registered','identity_submitted','toman_deposit_submitted'));

create or replace function marketplace_private.toman_deposit_admin_report()
returns trigger language plpgsql security definer set search_path='' as $$
declare method_label text;amount_label text;customer_label text;
begin
 if new.status<>'submitted' then return new;end if;
 if tg_op='UPDATE' then
  if old.status='submitted' then return new;end if;
 end if;
 method_label:=case new.method when 'gateway' then 'درگاه پرداخت' when 'instant_bank' then 'واریز بانکی آنی'
  when 'card_transfer' then 'کارت به کارت' when 'paya' then 'پایا (شناسه‌دار)'
  when 'account_transfer' then 'سپرده به سپرده' when 'direct_debit' then 'برداشت خودکار' else new.method end;
 amount_label:=translate(to_char(new.amount_rial/10,'FM999,999,999,999,990'),'0123456789,','۰۱۲۳۴۵۶۷۸۹٬');
 select coalesce(nullif(trim(concat_ws(' ',first_name,last_name)),''),nullif(username,''),'کاربر پلانک')
 into customer_label from marketplace_private.customer_profiles where user_id=new.user_id;
 insert into marketplace_private.admin_notifications(event_key,event_type,user_id,title,body,action_url,created_at)
 values('toman-deposit-report:'||new.id,'toman_deposit_submitted',new.user_id,
  jsonb_build_object('fa','گزارش واریز کاربر · '||method_label),
  jsonb_build_object('fa',coalesce(customer_label,'کاربر پلانک')||' واریز '||amount_label||' تومان به روش «'||method_label||'» را اعلام کرده است. شناسه پیگیری: '||translate(new.transfer_reference,'0123456789','۰۱۲۳۴۵۶۷۸۹')||'. وضعیت: در انتظار تطبیق بانکی؛ این گزارش به معنی تأیید پرداخت یا افزایش موجودی نیست.'),
  '/customers/'||new.user_id||'/activity?category=wallet',coalesce(new.submitted_at,clock_timestamp()))
 on conflict(event_key) do nothing;
 return new;
end$$;
revoke all on function marketplace_private.toman_deposit_admin_report() from public,anon,authenticated,service_role;
drop trigger if exists toman_deposit_admin_report on marketplace_private.toman_deposit_requests;
create trigger toman_deposit_admin_report after insert or update on marketplace_private.toman_deposit_requests
 for each row when(new.status='submitted') execute function marketplace_private.toman_deposit_admin_report();
commit;
