-- Deploy camper:edit_booking to pg
-- requires: roles
-- requires: schema_camper
-- requires: booking
-- requires: booking__payment_fields
-- requires: booking__stay
-- requires: booking_campsite

begin;

set search_path to camper, public;

create or replace function edit_booking(bid integer, customer_name text, customer_address text, customer_post_code text, customer_city text, customer_country_code text, customer_email email, customer_phone text, customer_lang_tag text, booking_status text, campsite_ids integer[]) returns void as
$$
begin
	update booking
	set holder_name = customer_name
	  , address = customer_address
	  , postal_code = customer_post_code
	  , city = customer_city
	  , country_code = customer_country_code
	  , email = customer_email
	  , phone = case when customer_phone is null then null else parse_packed_phone_number(customer_phone, coalesce(customer_country_code, 'ES')) end
	  , lang_tag = coalesce(customer_lang_tag, 'und')
	  , booking_status = edit_booking.booking_status
	where booking_id = bid
	;

	delete from booking_campsite
	where booking_id = bid;

	insert into booking_campsite
	select bid
	     , campsite_id
	     , stay
	from booking, unnest(campsite_ids) as campsite(campsite_id)
	where booking_id = bid
	;
end
$$
	language plpgsql
;

revoke execute on function edit_booking(integer, text, text, text, text, text, email, text, text, text, integer[]) from public;
grant execute on function edit_booking(integer, text, text, text, text, text, email, text, text, text, integer[]) to employee;
grant execute on function edit_booking(integer, text, text, text, text, text, email, text, text, text, integer[]) to admin;

commit;
