-- worker_rules: source-of-truth for rules.md content shared between
-- the dashboard editor and the worker daemon.
--
-- The daemon mirrors rows from this table to local rules.md files:
--   scope = 'global'              → ~/.devist/worker/rules.md
--   scope = 'project:<name>'      → <monitor>/<name>/.devist/rules.md
--
-- Apply once per Supabase project after 0001..0003.

create table if not exists public.worker_rules (
    scope       text        primary key,
    content     text        not null default '',
    updated_at  timestamptz not null default now()
);

-- Auto-bump updated_at on UPDATE.
create or replace function public.worker_rules_touch_updated_at()
returns trigger language plpgsql as $$
begin
    new.updated_at := now();
    return new;
end;
$$;

drop trigger if exists worker_rules_touch on public.worker_rules;
create trigger worker_rules_touch
    before update on public.worker_rules
    for each row execute function public.worker_rules_touch_updated_at();

alter table public.worker_rules enable row level security;

drop policy if exists "auth read rules" on public.worker_rules;
create policy "auth read rules"
    on public.worker_rules
    for select
    to authenticated
    using (true);

drop policy if exists "auth write rules" on public.worker_rules;
create policy "auth write rules"
    on public.worker_rules
    for all
    to authenticated
    using (true)
    with check (true);

alter publication supabase_realtime add table public.worker_rules;
