-- FROGLEAF MULTI-SHOP POS — initial tenant-safe schema
-- Run only in the NEW, separate Multi-Shop POS Supabase project.
-- Do NOT run this in the Smart Card Supabase project.
-- Existing single-shop HTML files are preserved in /legacy and are NOT overwritten.

create extension if not exists pgcrypto;

create table if not exists public.tenants (
  id uuid primary key default gen_random_uuid(),
  shop_code text not null unique,
  shop_name text not null,
  shop_type text not null check (shop_type in ('computer','phone','grocery','general')),
  currency_code text not null default 'LKR',
  logo_url text,
  app_icon_url text,
  theme_json jsonb not null default '{}'::jsonb,
  public_enabled boolean not null default true,
  status text not null default 'active' check (status in ('active','suspended','closed')),
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create table if not exists public.user_profiles (
  user_id uuid primary key references auth.users(id) on delete cascade,
  display_name text,
  phone text,
  created_at timestamptz not null default now()
);

-- Central platform admins are intentionally separate from shop staff.
-- This table grants platform configuration access only, not daily shop operations.
create table if not exists public.platform_admins (
  user_id uuid primary key references auth.users(id) on delete cascade,
  granted_at timestamptz not null default now(),
  granted_by uuid references auth.users(id)
);

create table if not exists public.shop_members (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null references public.tenants(id) on delete cascade,
  user_id uuid not null references auth.users(id) on delete cascade,
  role text not null check (role in ('owner','manager','cashier')),
  is_active boolean not null default true,
  created_at timestamptz not null default now(),
  unique (tenant_id,user_id)
);

create table if not exists public.categories (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null references public.tenants(id) on delete cascade,
  name text not null,
  sort_order integer not null default 0,
  is_active boolean not null default true,
  created_at timestamptz not null default now(),
  unique (tenant_id,name), unique (tenant_id,id)
);

-- legacy_data keeps un-mapped fields from the old POS during migration.
-- Do not delete legacy_data until every field has been reconciled and verified.
create table if not exists public.products (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null references public.tenants(id) on delete cascade,
  category_id uuid,
  product_name text not null,
  sku text,
  barcode text,
  serial_number text,
  imei text,
  photo_url text,
  featured boolean not null default false,
  retail_price numeric(14,2) not null default 0 check (retail_price >= 0),
  wholesale_price numeric(14,2) not null default 0 check (wholesale_price >= 0),
  purchase_price numeric(14,2) not null default 0 check (purchase_price >= 0),
  stock_quantity numeric(14,3) not null default 0,
  unit text not null default 'piece',
  batch_number text,
  expiry_date date,
  warranty_months integer,
  supplier_id uuid,
  is_active boolean not null default true,
  legacy_id text,
  legacy_data jsonb not null default '{}'::jsonb,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  foreign key (tenant_id,category_id) references public.categories(tenant_id,id),
  unique (tenant_id,id)
);
create index if not exists products_tenant_name_idx on public.products(tenant_id,product_name);
create index if not exists products_tenant_barcode_idx on public.products(tenant_id,barcode);
create index if not exists products_tenant_serial_idx on public.products(tenant_id,serial_number);
create index if not exists products_tenant_imei_idx on public.products(tenant_id,imei);

create table if not exists public.suppliers (
  id uuid primary key default gen_random_uuid(), tenant_id uuid not null references public.tenants(id) on delete cascade,
  supplier_name text not null, phone text, address text, notes text,
  created_at timestamptz not null default now(), unique (tenant_id,id)
);
alter table public.products drop constraint if exists products_supplier_id_fkey;
alter table public.products add constraint products_supplier_tenant_fk
  foreign key (tenant_id,supplier_id) references public.suppliers(tenant_id,id);

create table if not exists public.wholesale_customers (
  id uuid primary key default gen_random_uuid(), tenant_id uuid not null references public.tenants(id) on delete cascade,
  user_id uuid references auth.users(id) on delete set null,
  customer_name text not null, username text, phone text, address text,
  credit_limit numeric(14,2) not null default 0, payment_terms_days integer not null default 0,
  is_active boolean not null default true, created_at timestamptz not null default now(),
  unique (tenant_id,id), unique (tenant_id,username)
);

create table if not exists public.stock_movements (
  id uuid primary key default gen_random_uuid(), tenant_id uuid not null references public.tenants(id) on delete cascade,
  product_id uuid not null, movement_type text not null check (movement_type in
    ('opening','purchase','sale','sale_return','purchase_return','transfer_in','transfer_out','damage','adjustment','count')),
  quantity_delta numeric(14,3) not null, unit_cost numeric(14,2), reference_type text, reference_id uuid,
  reason text, created_by uuid references auth.users(id), created_at timestamptz not null default now(),
  foreign key (tenant_id,product_id) references public.products(tenant_id,id)
);
create index if not exists stock_movements_product_idx on public.stock_movements(tenant_id,product_id,created_at desc);

create table if not exists public.sales (
  id uuid primary key default gen_random_uuid(), tenant_id uuid not null references public.tenants(id) on delete cascade,
  bill_number text not null, customer_name text, customer_phone text,
  sale_mode text not null default 'retail' check (sale_mode in ('retail','wholesale')),
  subtotal numeric(14,2) not null default 0, discount numeric(14,2) not null default 0,
  total numeric(14,2) not null default 0, amount_received numeric(14,2) not null default 0,
  balance numeric(14,2) not null default 0, payment_status text not null default 'paid',
  status text not null default 'completed', created_by uuid references auth.users(id),
  created_at timestamptz not null default now(), unique (tenant_id,bill_number), unique (tenant_id,id)
);
create table if not exists public.sale_items (
  id uuid primary key default gen_random_uuid(), tenant_id uuid not null references public.tenants(id) on delete cascade,
  sale_id uuid not null, product_id uuid not null, product_name_snapshot text not null,
  quantity numeric(14,3) not null, unit_price numeric(14,2) not null, line_total numeric(14,2) not null,
  created_at timestamptz not null default now(),
  foreign key (tenant_id,sale_id) references public.sales(tenant_id,id) on delete cascade,
  foreign key (tenant_id,product_id) references public.products(tenant_id,id)
);

create table if not exists public.retail_orders (
  id uuid primary key default gen_random_uuid(), tenant_id uuid not null references public.tenants(id) on delete cascade,
  order_number text not null, customer_name text not null, customer_phone text not null,
  delivery_address text, order_items jsonb not null default '[]'::jsonb,
  total numeric(14,2) not null default 0, order_status text not null default 'pending',
  created_at timestamptz not null default now(), unique (tenant_id,order_number)
);
create table if not exists public.wholesale_orders (
  id uuid primary key default gen_random_uuid(), tenant_id uuid not null references public.tenants(id) on delete cascade,
  wholesale_customer_id uuid not null, order_number text not null, order_items jsonb not null default '[]'::jsonb,
  total numeric(14,2) not null default 0, order_status text not null default 'pending',
  created_at timestamptz not null default now(),
  foreign key (tenant_id,wholesale_customer_id) references public.wholesale_customers(tenant_id,id),
  unique (tenant_id,order_number)
);

create table if not exists public.purchase_invoices (
  id uuid primary key default gen_random_uuid(), tenant_id uuid not null references public.tenants(id) on delete cascade,
  supplier_id uuid, invoice_number text, total numeric(14,2) not null default 0,
  invoice_date date not null default current_date, notes text, created_by uuid references auth.users(id),
  created_at timestamptz not null default now(),
  foreign key (tenant_id,supplier_id) references public.suppliers(tenant_id,id)
);
create table if not exists public.expenses (
  id uuid primary key default gen_random_uuid(), tenant_id uuid not null references public.tenants(id) on delete cascade,
  expense_title text not null, amount numeric(14,2) not null check (amount >= 0), expense_date date not null default current_date,
  notes text, created_by uuid references auth.users(id), created_at timestamptz not null default now()
);
create table if not exists public.cash_closings (
  id uuid primary key default gen_random_uuid(), tenant_id uuid not null references public.tenants(id) on delete cascade,
  closing_date date not null default current_date, opening_cash numeric(14,2) not null default 0,
  cash_sales numeric(14,2) not null default 0, cash_received numeric(14,2) not null default 0,
  expenses numeric(14,2) not null default 0, counted_cash numeric(14,2) not null default 0,
  difference numeric(14,2) not null default 0, closed_by uuid references auth.users(id), created_at timestamptz not null default now()
);
create table if not exists public.activity_logs (
  id uuid primary key default gen_random_uuid(), tenant_id uuid references public.tenants(id) on delete cascade,
  actor_id uuid references auth.users(id), action text not null, entity_type text, entity_id uuid,
  details jsonb not null default '{}'::jsonb, created_at timestamptz not null default now()
);

-- Access helper functions. SECURITY DEFINER avoids recursive RLS evaluation.
create or replace function public.is_shop_member(p_tenant uuid)
returns boolean language sql stable security definer set search_path = public
as $$ select exists(select 1 from public.shop_members m where m.tenant_id=p_tenant and m.user_id=auth.uid() and m.is_active); $$;
create or replace function public.shop_role(p_tenant uuid)
returns text language sql stable security definer set search_path = public
as $$ select m.role from public.shop_members m where m.tenant_id=p_tenant and m.user_id=auth.uid() and m.is_active limit 1; $$;
create or replace function public.can_manage_shop(p_tenant uuid)
returns boolean language sql stable security definer set search_path = public
as $$ select coalesce(public.shop_role(p_tenant) in ('owner','manager'),false); $$;

alter table public.tenants enable row level security;
alter table public.user_profiles enable row level security;
alter table public.platform_admins enable row level security;
alter table public.shop_members enable row level security;
alter table public.categories enable row level security;
alter table public.products enable row level security;
alter table public.suppliers enable row level security;
alter table public.wholesale_customers enable row level security;
alter table public.stock_movements enable row level security;
alter table public.sales enable row level security;
alter table public.sale_items enable row level security;
alter table public.retail_orders enable row level security;
alter table public.wholesale_orders enable row level security;
alter table public.purchase_invoices enable row level security;
alter table public.expenses enable row level security;
alter table public.cash_closings enable row level security;
alter table public.activity_logs enable row level security;

-- Shop users see only their own tenant. Platform admins get no blanket business-data access.
create policy tenant_member_read on public.tenants for select using (public.is_shop_member(id));
create policy tenants_public_read on public.tenants for select using (public.public_enabled and status='active');
create policy tenant_owner_update on public.tenants for update using (public.shop_role(id)='owner') with check (public.shop_role(id)='owner');
create policy profile_self on public.user_profiles for all using (user_id=auth.uid()) with check (user_id=auth.uid());
create policy platform_admin_self_read on public.platform_admins for select using (user_id=auth.uid());
create policy shop_members_read on public.shop_members for select using (public.is_shop_member(tenant_id));
create policy shop_members_owner_manage on public.shop_members for all using (public.shop_role(tenant_id)='owner') with check (public.shop_role(tenant_id)='owner');

-- Public catalogue: active items only, only for an enabled public shop.
create policy categories_public_read on public.categories for select using (
  is_active and exists(select 1 from public.tenants t where t.id=tenant_id and t.public_enabled and t.status='active')
);
create policy categories_staff_write on public.categories for all using (public.can_manage_shop(tenant_id)) with check (public.can_manage_shop(tenant_id));
create policy products_public_read on public.products for select using (
  is_active and exists(select 1 from public.tenants t where t.id=tenant_id and t.public_enabled and t.status='active')
);
create policy products_staff_write on public.products for all using (public.can_manage_shop(tenant_id)) with check (public.can_manage_shop(tenant_id));
create policy suppliers_staff_read on public.suppliers for select using (public.is_shop_member(tenant_id));
create policy suppliers_manager_write on public.suppliers for all using (public.can_manage_shop(tenant_id)) with check (public.can_manage_shop(tenant_id));
create policy wholesale_customers_staff_read on public.wholesale_customers for select using (public.is_shop_member(tenant_id) or user_id=auth.uid());
create policy wholesale_customers_manager_write on public.wholesale_customers for all using (public.can_manage_shop(tenant_id)) with check (public.can_manage_shop(tenant_id));
create policy stock_staff_read on public.stock_movements for select using (public.is_shop_member(tenant_id));
create policy stock_manager_insert on public.stock_movements for insert with check (public.can_manage_shop(tenant_id));
create policy sales_staff_read on public.sales for select using (public.is_shop_member(tenant_id));
create policy sales_staff_insert on public.sales for insert with check (public.is_shop_member(tenant_id) and created_by=auth.uid());
create policy sale_items_staff_read on public.sale_items for select using (public.is_shop_member(tenant_id));
create policy sale_items_staff_insert on public.sale_items for insert with check (public.is_shop_member(tenant_id));
-- Public retail orders must be created through a server-side Edge Function/RPC that
-- re-reads product prices and stock. No direct anon INSERT policy is granted here.
create policy retail_orders_staff_read on public.retail_orders for select using (public.is_shop_member(tenant_id));
create policy retail_orders_staff_update on public.retail_orders for update using (public.is_shop_member(tenant_id)) with check (public.is_shop_member(tenant_id));
create policy wholesale_orders_staff_read on public.wholesale_orders for select using (public.is_shop_member(tenant_id));
create policy wholesale_orders_customer_read on public.wholesale_orders for select using (
  exists(select 1 from public.wholesale_customers w where w.tenant_id=tenant_id and w.id=wholesale_customer_id and w.user_id=auth.uid())
);
create policy purchase_staff_read on public.purchase_invoices for select using (public.is_shop_member(tenant_id));
create policy purchase_manager_write on public.purchase_invoices for all using (public.can_manage_shop(tenant_id)) with check (public.can_manage_shop(tenant_id));
create policy expenses_staff_read on public.expenses for select using (public.is_shop_member(tenant_id));
create policy expenses_manager_write on public.expenses for all using (public.can_manage_shop(tenant_id)) with check (public.can_manage_shop(tenant_id));
create policy cash_staff_read on public.cash_closings for select using (public.is_shop_member(tenant_id));
create policy cash_manager_write on public.cash_closings for all using (public.can_manage_shop(tenant_id)) with check (public.can_manage_shop(tenant_id));
create policy activity_staff_read on public.activity_logs for select using (tenant_id is not null and public.is_shop_member(tenant_id));
create policy activity_staff_insert on public.activity_logs for insert with check (tenant_id is null or public.is_shop_member(tenant_id));

-- IMPORTANT: public retail orders must use a server-side validated Edge Function/RPC.
-- IMPORTANT: stock quantity is not directly editable by cashier accounts.
-- Use stock_movements and a reviewed server-side transaction/RPC to update stock.
-- Never grant anon/authenticated clients direct UPDATE on stock_quantity in production.
