-- Sync manual_required notification_status into unified "Требуется ручное управление" workflow
-- and clear it when logistics takes action (changes delivery_status).

-- 1. Backfill: normalize existing rows where notification_status is manual_required
--    and delivery_status is still pending/manual_confirmation_required.
update public.order_groups
set delivery_status = 'pending_confirmation',
    updated_at = timezone('utc', now())
where notification_status = 'manual_required'
  and delivery_status = 'manual_confirmation_required';

-- 2. When notification_status becomes manual_required, ensure delivery_status stays pending
--    so the group appears in the unified "Требуется ручное управление" bucket.
create or replace function public.sync_manual_required_notification()
returns trigger
language plpgsql
security definer
set search_path = public
as $$
begin
  -- Only act when notification_status changed to manual_required
  if new.notification_status = 'manual_required'
     and (old is null or old.notification_status is distinct from new.notification_status) then
    if new.delivery_status is null or new.delivery_status = 'manual_confirmation_required' then
      new.delivery_status := 'pending_confirmation';
    end if;
  end if;
  return new;
end;
$$;

drop trigger if exists sync_manual_required_notification_trigger on public.order_groups;
create trigger sync_manual_required_notification_trigger
  before insert or update on public.order_groups
  for each row
  execute function public.sync_manual_required_notification();

-- 3. When delivery_status is changed by logistics (away from pending/manual_confirmation_required),
--    clear notification_status so the group leaves the manual-work bucket.
create or replace function public.clear_manual_required_on_action()
returns trigger
language plpgsql
security definer
set search_path = public
as $$
begin
  if old.delivery_status in ('pending_confirmation', 'manual_confirmation_required')
     and new.delivery_status not in ('pending_confirmation', 'manual_confirmation_required')
     and old.notification_status = 'manual_required' then
    new.notification_status := 'confirmed';
  end if;
  return new;
end;
$$;

drop trigger if exists clear_manual_required_on_action_trigger on public.order_groups;
create trigger clear_manual_required_on_action_trigger
  before update on public.order_groups
  for each row
  when (new.delivery_status is distinct from old.delivery_status)
  execute function public.clear_manual_required_on_action();
