CREATE OR REPLACE FUNCTION public.create_booking_atomic(
  p_account_id uuid,
  p_room_id uuid,
  p_guest_id uuid DEFAULT NULL,
  p_check_in date DEFAULT NULL,
  p_check_out date DEFAULT NULL,
  p_adults integer DEFAULT 1,
  p_children integer DEFAULT 0,
  p_status text DEFAULT 'confirmed',
  p_total_price numeric DEFAULT NULL,
  p_notes text DEFAULT NULL
)
RETURNS uuid
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $fn$
DECLARE
  v_room record;
  v_computed_price numeric(10,2);
  v_booking_id uuid;
BEGIN
  SELECT * INTO v_room FROM public.rooms WHERE id = p_room_id FOR UPDATE;
  IF v_room IS NULL THEN
    RAISE EXCEPTION 'Room % not found', p_room_id USING ERRCODE = 'P0002';
  END IF;
  IF p_check_in IS NULL OR p_check_out IS NULL THEN
    RAISE EXCEPTION 'check_in and check_out dates are required' USING ERRCODE = 'P0001';
  END IF;
  IF p_check_out <= p_check_in THEN
    RAISE EXCEPTION 'check_out must be after check_in' USING ERRCODE = 'P0001';
  END IF;
  IF (p_adults + p_children) > v_room.capacity THEN
    RAISE EXCEPTION 'Total guests exceed room capacity' USING ERRCODE = 'P0001';
  END IF;

  IF p_total_price IS NOT NULL THEN
    v_computed_price := p_total_price;
  ELSE
    v_computed_price := v_room.price_per_night * (p_check_out - p_check_in);
  END IF;

  INSERT INTO public.bookings (
    account_id, room_id, guest_id, check_in, check_out,
    adults, children, status, total_price, notes
  ) VALUES (
    p_account_id, p_room_id, p_guest_id, p_check_in, p_check_out,
    p_adults, p_children, p_status, v_computed_price, p_notes
  )
  RETURNING id INTO v_booking_id;

  RETURN v_booking_id;
END;
$fn$;
