-- Deploy camper:booking to pg
-- requires: roles
-- requires: schema_camper
-- requires: company
-- requires: user_profile
-- requires: campsite_type
-- requires: booking_status

begin;

set search_path to camper, public;

create table booking (
	booking_id integer generated by default as identity primary key,
	company_id integer not null references company,
	slug uuid not null unique default gen_random_uuid(),
	campsite_type_id integer not null references campsite_type,
	holder_name text not null constraint holder_name_not_empty check (length(trim(holder_name)) > 0),
	arrival_date date not null,
	departure_date date not null constraint departure_after_arrival check (departure_date > arrival_date),
	number_dogs integer not null constraint number_dogs_nonnegative check (number_dogs >= 0),
	acsi_card boolean not null,
	booking_status text not null default 'created' references booking_status,
	created_at timestamptz not null default current_timestamp
);

grant select, insert, update on table booking to employee;
grant select, insert, update, delete on table booking to admin;

alter table booking enable row level security;

create policy select_from_company
on booking
for select
using (
	company_id in (select company_id from user_profile)
)
;

create policy insert_to_company
on booking
for insert
with check (
	company_id in (select company_id from user_profile)
)
;

create policy update_company
on booking
for update
using (
	company_id in (select company_id from user_profile)
)
;

create policy delete_from_company
on booking
for delete
using (
	company_id in (select company_id from user_profile)
)
;

commit;
