-- Tablecall: multi-restaurant schema and access policies
create extension if not exists pgcrypto;

create type public.membership_role as enum ('admin','staff');
create type public.request_status as enum ('new','acknowledged','completed');

create table public.restaurants (
  id uuid primary key default gen_random_uuid(),
  name text not null check (length(trim(name)) between 1 and 120),
  slug text not null unique check (slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'),
  logo_url text,
  brand_color text not null default '#335c45' check (brand_color ~ '^#[0-9A-Fa-f]{6}$'),
  welcome_message text not null default 'Choose what you need and our team will be with you shortly.' check(length(welcome_message)<=240),
  active boolean not null default true,
  created_at timestamptz not null default now(), updated_at timestamptz not null default now()
);
create table public.profiles (
  id uuid primary key references auth.users(id) on delete cascade,
  display_name text, created_at timestamptz not null default now(), updated_at timestamptz not null default now()
);
create table public.restaurant_memberships (
  id uuid primary key default gen_random_uuid(), restaurant_id uuid not null references public.restaurants(id) on delete cascade,
  user_id uuid not null references auth.users(id) on delete cascade, role public.membership_role not null default 'staff',
  active boolean not null default true, created_at timestamptz not null default now(), unique(restaurant_id,user_id)
);
create table public.restaurant_tables (
  id uuid primary key default gen_random_uuid(), restaurant_id uuid not null references public.restaurants(id) on delete cascade,
  label text not null check(length(trim(label)) between 1 and 60), slug text not null check(slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'),
  active boolean not null default true, created_at timestamptz not null default now(), unique(restaurant_id,slug), unique(restaurant_id,label)
);
create table public.service_types (
  id uuid primary key default gen_random_uuid(), restaurant_id uuid not null references public.restaurants(id) on delete cascade,
  name text not null check(length(trim(name)) between 1 and 60), slug text not null check(slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'),
  icon text not null default 'help', enabled boolean not null default true, sort_order int not null default 0,
  created_at timestamptz not null default now(), unique(restaurant_id,slug)
);
create table public.service_requests (
  id uuid primary key default gen_random_uuid(), restaurant_id uuid not null references public.restaurants(id) on delete cascade,
  table_id uuid not null references public.restaurant_tables(id) on delete restrict,
  service_type_id uuid references public.service_types(id) on delete set null,
  request_type text not null check(length(trim(request_type)) between 1 and 60),
  message text check(message is null or length(message)<=220), status public.request_status not null default 'new',
  created_by uuid references auth.users(id) on delete set null,
  created_at timestamptz not null default now(), acknowledged_at timestamptz, completed_at timestamptz,
  check((status <> 'completed') or completed_at is not null)
);
create index memberships_user_idx on public.restaurant_memberships(user_id,active);
create index tables_restaurant_idx on public.restaurant_tables(restaurant_id,active);
create index service_types_restaurant_idx on public.service_types(restaurant_id,enabled,sort_order);
create index service_requests_restaurant_time_idx on public.service_requests(restaurant_id,created_at desc);
create index service_requests_table_idx on public.service_requests(table_id,created_at desc);
create index service_requests_status_idx on public.service_requests(restaurant_id,status,created_at);

create or replace function public.touch_updated_at() returns trigger language plpgsql set search_path=public as $$ begin new.updated_at=now(); return new; end $$;
create trigger restaurants_touch before update on public.restaurants for each row execute function public.touch_updated_at();
create trigger profiles_touch before update on public.profiles for each row execute function public.touch_updated_at();
create or replace function public.handle_new_user() returns trigger language plpgsql security definer set search_path=public as $$
begin insert into public.profiles(id,display_name) values(new.id,coalesce(new.raw_user_meta_data->>'name','')) on conflict(id) do nothing; return new; end $$;
create trigger on_auth_user_created after insert on auth.users for each row execute function public.handle_new_user();

create or replace function public.is_restaurant_member(rid uuid) returns boolean language sql stable security definer set search_path=public as $$
 select exists(select 1 from public.restaurant_memberships m where m.restaurant_id=rid and m.user_id=auth.uid() and m.active)
$$;
create or replace function public.is_restaurant_admin(rid uuid) returns boolean language sql stable security definer set search_path=public as $$
 select exists(select 1 from public.restaurant_memberships m where m.restaurant_id=rid and m.user_id=auth.uid() and m.active and m.role='admin')
$$;
revoke all on function public.is_restaurant_member(uuid) from public;
revoke all on function public.is_restaurant_admin(uuid) from public;
grant execute on function public.is_restaurant_member(uuid),public.is_restaurant_admin(uuid) to authenticated;

alter table public.restaurants enable row level security;
alter table public.profiles enable row level security;
alter table public.restaurant_memberships enable row level security;
alter table public.restaurant_tables enable row level security;
alter table public.service_types enable row level security;
alter table public.service_requests enable row level security;

create policy "members read own restaurants" on public.restaurants for select to authenticated using(public.is_restaurant_member(id));
create policy "guests read active restaurant brand" on public.restaurants for select to anon using(active);
create policy "admins update own restaurants" on public.restaurants for update to authenticated using(public.is_restaurant_admin(id)) with check(public.is_restaurant_admin(id));
create policy "users read own profile" on public.profiles for select to authenticated using(id=auth.uid());
create policy "users update own profile" on public.profiles for update to authenticated using(id=auth.uid()) with check(id=auth.uid());
create policy "members read restaurant memberships" on public.restaurant_memberships for select to authenticated using(public.is_restaurant_member(restaurant_id));
create policy "admins manage memberships" on public.restaurant_memberships for all to authenticated using(public.is_restaurant_admin(restaurant_id)) with check(public.is_restaurant_admin(restaurant_id));
create policy "members read tables" on public.restaurant_tables for select to authenticated using(public.is_restaurant_member(restaurant_id));
create policy "guests read active table labels" on public.restaurant_tables for select to anon using(active and exists(select 1 from public.restaurants r where r.id=restaurant_id and r.active));
create policy "admins manage tables" on public.restaurant_tables for all to authenticated using(public.is_restaurant_admin(restaurant_id)) with check(public.is_restaurant_admin(restaurant_id));
create policy "members read services" on public.service_types for select to authenticated using(public.is_restaurant_member(restaurant_id));
create policy "guests read enabled request types" on public.service_types for select to anon using(enabled and exists(select 1 from public.restaurants r where r.id=restaurant_id and r.active));
create policy "admins manage services" on public.service_types for all to authenticated using(public.is_restaurant_admin(restaurant_id)) with check(public.is_restaurant_admin(restaurant_id));
create policy "members read requests" on public.service_requests for select to authenticated using(public.is_restaurant_member(restaurant_id));
create policy "staff update requests" on public.service_requests for update to authenticated using(public.is_restaurant_member(restaurant_id)) with check(public.is_restaurant_member(restaurant_id));

create or replace function public.guard_service_request_update() returns trigger language plpgsql set search_path=public as $$
begin
 if new.id<>old.id or new.restaurant_id<>old.restaurant_id or new.table_id<>old.table_id or
    new.service_type_id is distinct from old.service_type_id or new.request_type<>old.request_type or
    new.message is distinct from old.message or new.created_by is distinct from old.created_by or new.created_at<>old.created_at then
   raise exception 'Request details cannot be changed';
 end if;
 if old.status='new' and new.status='acknowledged' then
   new.acknowledged_at=now(); new.completed_at=null;
 elsif old.status in ('new','acknowledged') and new.status='completed' then
   new.acknowledged_at=coalesce(old.acknowledged_at,now()); new.completed_at=now();
 else
   raise exception 'Invalid request status transition';
 end if;
 return new;
end $$;
create trigger guard_service_request_update before update on public.service_requests for each row execute function public.guard_service_request_update();

-- Anonymous guest requests enter only through this validating function. No guest table/request read policy exists.
create or replace function public.create_service_request(p_table_id uuid,p_service_type_id uuid,p_message text default null,p_customer_token text default null)
returns uuid language plpgsql security definer set search_path=public,auth as $$
declare t public.restaurant_tables%rowtype; s public.service_types%rowtype; new_id uuid;
begin
 if p_message is not null and length(p_message)>220 then raise exception 'Message is too long'; end if;
 select * into t from public.restaurant_tables where id=p_table_id and active;
 if not found then raise exception 'Invalid or inactive table'; end if;
 select * into s from public.service_types where id=p_service_type_id and restaurant_id=t.restaurant_id and enabled;
 if not found then raise exception 'Invalid or unavailable request type'; end if;
 if exists(select 1 from public.service_requests where table_id=t.id and service_type_id=s.id and status<>'completed' and created_at>now()-interval '2 minutes') then
   raise exception 'A matching request is already active';
 end if;
 insert into public.service_requests(restaurant_id,table_id,service_type_id,request_type,message)
 values(t.restaurant_id,t.id,s.id,s.name,nullif(trim(p_message),'')) returning id into new_id;
 return new_id;
end $$;
revoke all on function public.create_service_request(uuid,uuid,text,text) from public;
grant execute on function public.create_service_request(uuid,uuid,text,text) to anon,authenticated;

-- Seed request types for each restaurant after creation using the setup SQL in README.
grant usage on schema public to anon,authenticated;
grant select on public.restaurants,public.restaurant_tables,public.service_types to anon;
grant select on public.restaurants,public.restaurant_tables,public.service_types to authenticated;
grant select,update on public.restaurants to authenticated;
grant select,insert,update,delete on public.restaurant_memberships,public.restaurant_tables,public.service_types to authenticated;
grant select on public.service_requests to authenticated;
grant update(status,acknowledged_at,completed_at) on public.service_requests to authenticated;
grant select,update on public.profiles to authenticated;

do $$ begin
 if not exists(select 1 from pg_publication_tables where pubname='supabase_realtime' and schemaname='public' and tablename='service_requests') then
   alter publication supabase_realtime add table public.service_requests;
 end if;
end $$;
