-- Patch: Add paid_storage status support for order_groups

-- 1. Add paid_storage_at column to order_groups if not exists
alter table public.order_groups add column if not exists paid_storage_at timestamptz;

-- 2. Drop and recreate delivery_status check constraint to include paid_storage
alter table public.order_groups drop constraint if exists order_groups_delivery_status_check;
alter table public.order_groups add constraint order_groups_delivery_status_check
  check (delivery_status in (
    'pending_confirmation',
    'manual_confirmation_required',
    'agreed',
    'driver_assigned',
    'loaded',
    'on_route',
    'delivered',
    'paid_storage',
    'problem',
    'cancelled'
  ));

-- 3. Update update_delivery_status to allow paid_storage without assigned driver
create or replace function public.update_delivery_status(
  p_order_group_id uuid,
  p_status text
)
returns boolean
language plpgsql
security definer
set search_path = public
as $$
declare
  v_assigned_driver_id uuid;
  v_current_status text;
begin
  select assigned_driver_id, delivery_status
  into v_assigned_driver_id, v_current_status
  from public.order_groups
  where id = p_order_group_id;

  -- Allow paid_storage status for any authenticated user with proper role
  -- (checked by RLS policy)
  if p_status = 'paid_storage' then
    update public.order_groups
    set delivery_status = p_status,
        paid_storage_at = timezone('utc', now()),
        updated_at = timezone('utc', now())
    where id = p_order_group_id;
    return true;
  end if;

  if v_assigned_driver_id is null then
    raise exception 'Группа не назначена водителю';
  end if;

  if v_assigned_driver_id != auth.uid() then
    raise exception 'Вы не назначены на эту доставку';
  end if;

  update public.order_groups
  set delivery_status = p_status,
      updated_at = timezone('utc', now())
  where id = p_order_group_id;

  return true;
end;
$$;

-- 4. Ensure proper grants
revoke execute on function public.update_delivery_status(uuid, text) from anon;
grant execute on function public.update_delivery_status(uuid, text) to authenticated;

