create table if not exists public.tenant_role_templates (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null references public.tenants(id) on delete cascade,
  code text not null,
  name text not null,
  description text,
  base_role text not null default 'tenant_operator'
    check (base_role in ('tenant_owner', 'tenant_admin', 'tenant_operator', 'teacher', 'sales', 'agent', 'student')),
  status text not null default 'active' check (status in ('active', 'disabled', 'archived')),
  permissions jsonb not null default '{}'::jsonb,
  menu_permissions jsonb not null default '{}'::jsonb,
  module_permissions jsonb not null default '{}'::jsonb,
  field_permissions jsonb not null default '{}'::jsonb,
  data_scope jsonb not null default '{}'::jsonb,
  is_system boolean not null default false,
  sort_order integer not null default 100,
  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(),
  unique (tenant_id, code)
);

comment on table public.tenant_role_templates is
  '租户自定义角色模板。成员仍保留系统 base role，模板提供权限、菜单、模块、字段和数据范围配置。';

alter table public.tenant_memberships
  add column if not exists role_template_id uuid references public.tenant_role_templates(id) on delete restrict;

create index if not exists idx_role_templates_tenant_status
  on public.tenant_role_templates(tenant_id, status, sort_order);

create index if not exists idx_memberships_role_template
  on public.tenant_memberships(role_template_id)
  where role_template_id is not null;

alter table public.tenant_role_templates enable row level security;

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