-- Add shift snapshot columns to swap_requests and update request_shift_swap RPC

ALTER TABLE public.swap_requests
  ADD COLUMN IF NOT EXISTS shift_type text;

ALTER TABLE public.swap_requests
  ADD COLUMN IF NOT EXISTS shift_start_time timestamptz;

ALTER TABLE public.swap_requests
  ADD COLUMN IF NOT EXISTS reliever_ids uuid[] DEFAULT '{}'::uuid[];

-- Update the request_shift_swap RPC so inserted swap_requests include a snapshot
-- of the referenced duty schedule (so UI can render shift info even after ownership changes)
CREATE OR REPLACE FUNCTION public.request_shift_swap(p_shift_id uuid, p_recipient_id uuid)
RETURNS uuid LANGUAGE plpgsql AS $$
DECLARE
  v_shift_record RECORD;
  v_recipient RECORD;
  v_new_id uuid;
BEGIN
  -- shift must exist and be owned by caller
  SELECT * INTO v_shift_record FROM public.duty_schedules WHERE id = p_shift_id;
  IF NOT FOUND THEN
    RAISE EXCEPTION 'shift not found';
  END IF;
  IF v_shift_record.user_id <> auth.uid() THEN
    RAISE EXCEPTION 'permission denied: only shift owner may request swap';
  END IF;

  -- recipient must exist and be it_staff
  SELECT id, role INTO v_recipient FROM public.profiles WHERE id = p_recipient_id;
  IF NOT FOUND THEN
    RAISE EXCEPTION 'recipient not found';
  END IF;
  IF v_recipient.role <> 'it_staff' THEN
    RAISE EXCEPTION 'recipient must be it_staff';
  END IF;

  INSERT INTO public.swap_requests(
      requester_id, recipient_id, shift_id, status, created_at, updated_at,
      shift_type, shift_start_time, reliever_ids
  )
  VALUES (
    auth.uid(), p_recipient_id, p_shift_id, 'pending', now(), now(),
    v_shift_record.shift_type, v_shift_record.start_time, v_shift_record.reliever_ids
  )
  RETURNING id INTO v_new_id;

  RETURN v_new_id;
END;
$$;