-- Invites table for invite-only registration
CREATE TABLE IF NOT EXISTS invites (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  token UUID UNIQUE NOT NULL DEFAULT gen_random_uuid(),
  email TEXT NOT NULL,
  created_by UUID REFERENCES auth.users(id) ON DELETE SET NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  expires_at TIMESTAMPTZ NOT NULL DEFAULT (NOW() + INTERVAL '7 days'),
  used_at TIMESTAMPTZ,
  used_by UUID REFERENCES auth.users(id) ON DELETE SET NULL
);

-- Enable RLS (all access goes through service role key in API routes)
ALTER TABLE invites ENABLE ROW LEVEL SECURITY;

-- Admins can read invites they created
CREATE POLICY "admins_read_invites" ON invites
  FOR SELECT USING (
    EXISTS (
      SELECT 1 FROM profiles
      WHERE profiles.id = auth.uid()
      AND profiles.role = 'admin'
    )
  );

-- Index for token lookups (invite acceptance)
CREATE INDEX IF NOT EXISTS invites_token_idx ON invites (token);

-- Index for listing by creator
CREATE INDEX IF NOT EXISTS invites_created_by_idx ON invites (created_by);
