create table if not exists public.question_bank_grants (
  id uuid primary key default gen_random_uuid(),
  source_question_bank_id uuid not null references public.question_banks(id) on delete cascade,
  grant_scope text not null default 'plans'
    check (grant_scope in ('all_active_tenants', 'plans', 'tenants', 'mixed')),
  allowed_plan_codes text[] not null default '{}'::text[],
  allowed_tenant_ids uuid[] not null default '{}'::uuid[],
  allowed_region_ids uuid[] not null default '{}'::uuid[],
  allowed_subject_ids uuid[] not null default '{}'::uuid[],
  status text not null default 'active' check (status in ('active', 'disabled', 'expired')),
  starts_at timestamptz,
  expires_at timestamptz,
  metadata 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()
);

create table if not exists public.tenant_question_bank_adoptions (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null references public.tenants(id) on delete cascade,
  source_question_bank_id uuid not null references public.question_banks(id) on delete cascade,
  grant_id uuid references public.question_bank_grants(id) on delete set null,
  target_question_bank_id uuid references public.question_banks(id) on delete set null,
  target_entry_id uuid references public.content_entries(id) on delete set null,
  target_collection_id uuid references public.question_collections(id) on delete set null,
  adoption_mode text not null default 'copied_snapshot'
    check (adoption_mode in ('copied_snapshot', 'reference')),
  status text not null default 'active' check (status in ('active', 'sync_pending', 'suspended', 'archived')),
  sync_status text not null default 'synced' check (sync_status in ('pending', 'synced', 'failed')),
  source_snapshot jsonb not null default '{}'::jsonb,
  copied_question_count integer not null default 0 check (copied_question_count >= 0),
  metadata 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,
  last_synced_at timestamptz,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  unique (tenant_id, source_question_bank_id)
);

create index if not exists idx_question_bank_grants_source_status
  on public.question_bank_grants(source_question_bank_id, status, starts_at, expires_at);

create index if not exists idx_question_bank_grants_allowed_tenants
  on public.question_bank_grants using gin(allowed_tenant_ids);

create index if not exists idx_question_bank_grants_allowed_plans
  on public.question_bank_grants using gin(allowed_plan_codes);

create index if not exists idx_tenant_question_bank_adoptions_tenant
  on public.tenant_question_bank_adoptions(tenant_id, status, updated_at desc);

alter table public.question_bank_grants enable row level security;
alter table public.tenant_question_bank_adoptions enable row level security;

drop policy if exists question_bank_grants_platform_admin on public.question_bank_grants;
create policy question_bank_grants_platform_admin on public.question_bank_grants
  for all
  using (app.is_platform_admin())
  with check (app.is_platform_admin());

drop policy if exists question_bank_grants_eligible_tenant_read on public.question_bank_grants;
create policy question_bank_grants_eligible_tenant_read on public.question_bank_grants
  for select
  using (
    status = 'active'
    and (starts_at is null or starts_at <= now())
    and (expires_at is null or expires_at > now())
    and exists (
      select 1
      from public.question_banks qb
      where qb.id = source_question_bank_id
        and qb.source_scope = 'platform'
        and qb.status = 'active'
    )
    and (
      (
        grant_scope = 'all_active_tenants'
        and exists (
          select 1
          from public.tenant_subscriptions ts
          where ts.tenant_id = app.current_tenant_id()
            and ts.status in ('trial', 'active')
            and (ts.expires_at is null or ts.expires_at > now())
        )
      )
      or (
        grant_scope in ('plans', 'mixed')
        and exists (
          select 1
          from public.tenant_subscriptions ts
          where ts.tenant_id = app.current_tenant_id()
            and ts.status in ('trial', 'active')
            and (ts.expires_at is null or ts.expires_at > now())
            and ts.plan_code = any(allowed_plan_codes)
        )
      )
      or (
        grant_scope in ('tenants', 'mixed')
        and app.current_tenant_id() = any(allowed_tenant_ids)
      )
    )
  );

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

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