-- ============================================================================
-- Migration: v66-security-audit-logs.sql
-- In-database security audit logs and administrative querying
-- ============================================================================

create table if not exists public.security_audit_logs (
  id uuid primary key default gen_random_uuid(),
  event_type text not null, -- 'security', 'registration', 'identity', 'moderation'
  action text not null,
  user_id uuid references auth.users(id) on delete set null,
  username text,
  email text,
  discord_id text,
  discord_username text,
  ip_address text,
  ip_hash text,
  endpoint text,
  details text,
  metadata jsonb default '{}'::jsonb,
  created_at timestamptz not null default now()
);

create index if not exists idx_security_audit_logs_user_id
  on public.security_audit_logs(user_id);

create index if not exists idx_security_audit_logs_discord_id
  on public.security_audit_logs(discord_id);

create index if not exists idx_security_audit_logs_username
  on public.security_audit_logs(username);

create index if not exists idx_security_audit_logs_email
  on public.security_audit_logs(email);

create index if not exists idx_security_audit_logs_event_type
  on public.security_audit_logs(event_type);

create index if not exists idx_security_audit_logs_created_at
  on public.security_audit_logs(created_at desc);

alter table public.security_audit_logs enable row level security;
revoke all on public.security_audit_logs from anon, authenticated;
grant all on public.security_audit_logs to service_role;
