create table if not exists public.tenant_student_supervision_rules (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null references public.tenants(id) on delete cascade,
  name text not null,
  status text not null default 'active'
    check (status in ('active', 'disabled', 'archived')),
  rules jsonb not null default '{}'::jsonb,
  schedule jsonb not null default '{}'::jsonb,
  class_id uuid references public.tenant_classes(id) on delete set null,
  assigned_to_user_id uuid references public.platform_users(id) on delete set null,
  limit_count integer not null default 20 check (limit_count between 1 and 100),
  metadata jsonb not null default '{}'::jsonb,
  last_run_at timestamptz,
  next_run_at timestamptz,
  last_result jsonb not null default '{}'::jsonb,
  created_by uuid references public.platform_users(id) on delete set null,
  updated_by uuid references public.platform_users(id) on delete set null,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

comment on table public.tenant_student_supervision_rules is
  'Tenant-scoped learning supervision rule templates used by admins and workers to generate student follow-up tasks.';

create index if not exists idx_student_supervision_rules_tenant_status
  on public.tenant_student_supervision_rules(tenant_id, status, next_run_at nulls first, created_at desc);

create index if not exists idx_student_supervision_rules_worker_due
  on public.tenant_student_supervision_rules(status, next_run_at nulls first)
  where status = 'active';

alter table public.tenant_student_supervision_rules enable row level security;

drop policy if exists tenant_isolation on public.tenant_student_supervision_rules;
create policy tenant_isolation on public.tenant_student_supervision_rules
  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_student_supervision_rules;
create trigger set_updated_at
  before update on public.tenant_student_supervision_rules
  for each row
  execute function app.touch_updated_at();
