-- v38: audited profile moderation and explicit moderation permission.

alter table public.profiles
  add column if not exists moderation_status text not null default 'active',
  add column if not exists suspended_until timestamptz,
  add column if not exists moderation_reason text,
  add column if not exists moderated_at timestamptz,
  add column if not exists moderated_by uuid references auth.users(id) on delete set null;

do $$
begin
  if not exists (
    select 1 from pg_constraint
    where conname = 'profiles_moderation_status_check'
      and conrelid = 'public.profiles'::regclass
  ) then
    alter table public.profiles
      add constraint profiles_moderation_status_check
      check (moderation_status in ('active', 'suspended', 'banned'));
  end if;
end $$;

alter table public.admin_access
  drop constraint if exists admin_access_known_permissions;
alter table public.admin_access
  add constraint admin_access_known_permissions check (
    permissions <@ array['profiles.read', 'profiles.edit', 'security.read', 'moderation.manage']::text[]
  );

create table if not exists public.admin_moderation_events (
  id bigint generated always as identity primary key,
  target_user_id uuid not null references auth.users(id) on delete cascade,
  actor_user_id uuid references auth.users(id) on delete set null,
  action text not null check (action in ('suspend', 'ban', 'reinstate')),
  reason text not null,
  suspended_until timestamptz,
  created_at timestamptz not null default now()
);

create index if not exists admin_moderation_events_target_created_idx
  on public.admin_moderation_events (target_user_id, created_at desc);

alter table public.admin_moderation_events enable row level security;
revoke all on public.admin_moderation_events from anon, authenticated;
grant all on public.admin_moderation_events to service_role;
grant usage, select on sequence public.admin_moderation_events_id_seq to service_role;
