-- FROGLEAF MULTI-SHOP POS — reliable retail order + WhatsApp notification
-- Run ONLY in the dedicated Multi-Shop POS Supabase project.
-- Each shop connects its own WhatsApp Business Account (WABA) for separate Meta billing.
-- Store access tokens in Supabase Vault; never place tokens in frontend code.

create extension if not exists supabase_vault with schema vault;

alter table public.retail_orders
  add column if not exists whatsapp_status text not null default 'pending'
    check (whatsapp_status in ('pending','sent','failed','not_configured')),
  add column if not exists whatsapp_attempts integer not null default 0,
  add column if not exists whatsapp_last_error text,
  add column if not exists whatsapp_sent_at timestamptz,
  add column if not exists delivery_method text,
  add column if not exists payment_method text;

create table if not exists public.shop_whatsapp_settings (
  tenant_id uuid primary key references public.tenants(id) on delete cascade,
  enabled boolean not null default false,
  recipient_phone text not null, -- shop owner's destination number, digits with country code
  phone_number_id text not null, -- sender phone_number_id from this shop's WABA
  waba_id text,
  access_token_secret_id uuid not null, -- secret stored in Supabase Vault
  order_template_name text not null default 'new_retail_order',
  template_language text not null default 'en',
  updated_at timestamptz not null default now()
);

create table if not exists public.whatsapp_delivery_log (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null references public.tenants(id) on delete cascade,
  retail_order_id uuid not null references public.retail_orders(id) on delete cascade,
  status text not null check (status in ('sent','failed')),
  attempt_number integer not null,
  provider_message_id text,
  error_message text,
  created_at timestamptz not null default now()
);
create index if not exists whatsapp_delivery_order_idx
  on public.whatsapp_delivery_log(tenant_id, retail_order_id, created_at desc);

alter table public.shop_whatsapp_settings enable row level security;
alter table public.whatsapp_delivery_log enable row level security;

drop policy if exists whatsapp_settings_owner_read on public.shop_whatsapp_settings;
create policy whatsapp_settings_owner_read on public.shop_whatsapp_settings
  for select using (public.shop_role(tenant_id) = 'owner');
drop policy if exists whatsapp_settings_owner_write on public.shop_whatsapp_settings;
create policy whatsapp_settings_owner_write on public.shop_whatsapp_settings
  for all using (public.shop_role(tenant_id) = 'owner')
  with check (public.shop_role(tenant_id) = 'owner');
drop policy if exists whatsapp_log_staff_read on public.whatsapp_delivery_log;
create policy whatsapp_log_staff_read on public.whatsapp_delivery_log
  for select using (public.is_shop_member(tenant_id));

-- Browser users may manage their shop's connection metadata, but never see Vault tokens.
revoke all on public.shop_whatsapp_settings from anon, authenticated;
grant select, insert, update, delete on public.shop_whatsapp_settings to authenticated;
revoke all on public.whatsapp_delivery_log from anon, authenticated;
grant select on public.whatsapp_delivery_log to authenticated;

-- Edge Functions call this service-role-only RPC. The Vault schema itself need not be
-- exposed through PostgREST. The decrypted token is returned only to service_role.
create or replace function public.get_shop_whatsapp_config(p_tenant_id uuid)
returns table (
  recipient_phone text,
  phone_number_id text,
  order_template_name text,
  template_language text,
  access_token text
)
language plpgsql
security definer
set search_path = public, vault
as $$
begin
  if auth.role() <> 'service_role' then
    raise exception 'service role required';
  end if;
  return query
    select s.recipient_phone, s.phone_number_id, s.order_template_name,
           s.template_language, v.decrypted_secret::text
    from public.shop_whatsapp_settings s
    join vault.decrypted_secrets v on v.id = s.access_token_secret_id
    where s.tenant_id = p_tenant_id and s.enabled = true;
end;
$$;
revoke all on function public.get_shop_whatsapp_config(uuid) from public, anon, authenticated;
grant execute on function public.get_shop_whatsapp_config(uuid) to service_role;

-- POS clients subscribe to INSERT events and RLS restricts rows to their own shop.
do $$
begin
  if not exists (
    select 1 from pg_publication_tables
    where pubname = 'supabase_realtime' and schemaname = 'public' and tablename = 'retail_orders'
  ) then
    alter publication supabase_realtime add table public.retail_orders;
  end if;
end $$;

-- Setup per shop (run as project admin after creating the shop's Vault secret):
-- select vault.create_secret('META_PER_SHOP_ACCESS_TOKEN', 'frogleaf-shop-a-whatsapp-token');
-- Use the returned secret UUID as access_token_secret_id in shop_whatsapp_settings.
-- The shop must have an approved WhatsApp Utility template matching the five body
-- parameters used by the Edge Function. Configure the actual template name/language.
-- Public retail orders are created ONLY by create-retail-order Edge Function.
