create table if not exists public.tenant_invoice_reminders (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null references public.tenants(id) on delete cascade,
  invoice_id uuid not null references public.tenant_invoices(id) on delete cascade,
  reminder_type text not null default 'overdue' check (reminder_type in ('due_soon', 'overdue', 'final_notice', 'manual')),
  channel text not null default 'manual' check (channel in ('manual', 'internal', 'sms', 'email', 'wechat', 'crm')),
  status text not null default 'pending' check (status in ('pending', 'sent', 'acknowledged', 'dismissed', 'failed')),
  reminder_date date not null default current_date,
  reminder_level integer not null default 1,
  due_date date,
  balance_cents_snapshot integer not null default 0,
  message text,
  metadata jsonb not null default '{}'::jsonb,
  created_by uuid references public.platform_users(id) on delete set null,
  sent_at timestamptz,
  acknowledged_at timestamptz,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create unique index if not exists uniq_tenant_invoice_reminders_daily
  on public.tenant_invoice_reminders(tenant_id, invoice_id, reminder_type, channel, reminder_date);

create index if not exists idx_tenant_invoice_reminders_tenant_status
  on public.tenant_invoice_reminders(tenant_id, status, reminder_date desc);

create index if not exists idx_tenant_invoice_reminders_invoice
  on public.tenant_invoice_reminders(invoice_id, reminder_date desc);

alter table public.tenant_invoice_reminders enable row level security;

drop policy if exists tenant_isolation on public.tenant_invoice_reminders;
create policy tenant_isolation on public.tenant_invoice_reminders
  for all
  using (tenant_id = app.current_tenant_id() or app.is_platform_admin())
  with check (tenant_id = app.current_tenant_id() or app.is_platform_admin());

drop trigger if exists set_updated_at on public.tenant_invoice_reminders;
create trigger set_updated_at
  before update on public.tenant_invoice_reminders
  for each row execute function app.touch_updated_at();
