-- Run this once inside your Supabase project's SQL Editor.
-- It creates the single table the app uses to store all of its data.
-- This mirrors how the app worked inside Claude: one JSON document per key.

create table if not exists app_storage (
  key text primary key,
  value text not null,
  shared boolean not null default false,
  updated_at timestamptz not null default now()
);

-- Row Level Security is enabled but wide open for now (phase 1: get it live).
-- Phase 2 should replace these policies with real role based rules,
-- see ROLES_AND_PERMISSIONS.md for the target design.

alter table app_storage enable row level security;

create policy "Allow all reads for now"
  on app_storage for select
  using (true);

create policy "Allow all writes for now"
  on app_storage for insert
  with check (true);

create policy "Allow all updates for now"
  on app_storage for update
  using (true);

create policy "Allow all deletes for now"
  on app_storage for delete
  using (true);

-- ============================================================
-- PROFILES TABLE
-- Run this once too. This is what makes accounts actually work.
-- Every person who logs in needs one row here, linked to their
-- Supabase Auth account by id.
-- ============================================================

create table if not exists profiles (
  id uuid primary key references auth.users(id) on delete cascade,
  full_name text not null,
  email text not null,
  role text not null check (role in ('admin', 'teacher', 'learning_assistant', 'parent')),
  student_ids uuid[] default '{}',      -- used for parents: the id(s) of their linked child/children
  grades_assigned text[] default '{}',  -- used for teachers/learning assistants: which grades they teach
  created_at timestamptz not null default now()
);

alter table profiles enable row level security;

-- Everyone who is logged in can read their own profile (needed for login to work at all)
create policy "Users can read their own profile"
  on profiles for select
  using (auth.uid() = id);

-- Phase 1: any logged in staff member can read every profile
-- (needed for admin screens later, and simplest for now)
create policy "Authenticated users can read all profiles"
  on profiles for select
  using (auth.role() = 'authenticated');

-- Only allow profile creation/edits from the Supabase dashboard for now (phase 1).
-- Phase 2 should replace this with a proper admin only policy once
-- there is an in app user management screen.
