create table if not exists public.ai_recommendation_reports (
  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 public.platform_users(id) on delete cascade,
  region_id uuid references public.regions(id) on delete set null,
  status text not null default 'generated'
    check (status in ('draft', 'generated', 'failed')),
  provider text not null default 'local_rules',
  model text,
  prompt_version text not null default 'school-recommendation-v1',
  input_payload jsonb not null default '{}'::jsonb,
  context_payload jsonb not null default '{}'::jsonb,
  result_payload jsonb not null default '{}'::jsonb,
  error_message text,
  generated_at timestamptz,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create index if not exists idx_ai_recommendation_reports_user
  on public.ai_recommendation_reports(tenant_id, user_id, created_at desc);

create index if not exists idx_ai_recommendation_reports_region
  on public.ai_recommendation_reports(tenant_id, region_id, created_at desc);

alter table public.ai_recommendation_reports enable row level security;

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