-- Create passkeys table for WebAuthn credential storage
CREATE TABLE IF NOT EXISTS public.passkeys (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  credential_id TEXT NOT NULL UNIQUE,
  public_key TEXT NOT NULL,
  sign_count INTEGER NOT NULL DEFAULT 0,
  transports TEXT[] DEFAULT ARRAY[]::TEXT[],
  backup_eligible BOOLEAN DEFAULT FALSE,
  backup_state BOOLEAN DEFAULT FALSE,
  aaguid UUID,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  last_used TIMESTAMP WITH TIME ZONE,
  friendly_name TEXT
);

-- Enable RLS on passkeys table
ALTER TABLE public.passkeys ENABLE ROW LEVEL SECURITY;

-- Create RLS policies for passkeys
CREATE POLICY "Users can view their own passkeys" ON public.passkeys
  FOR SELECT USING (auth.uid() = user_id);

CREATE POLICY "Users can insert their own passkeys" ON public.passkeys
  FOR INSERT WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can delete their own passkeys" ON public.passkeys
  FOR DELETE USING (auth.uid() = user_id);

CREATE POLICY "Users can update their own passkeys" ON public.passkeys
  FOR UPDATE USING (auth.uid() = user_id);

-- Create index for faster credential lookups
CREATE INDEX idx_passkeys_credential_id ON public.passkeys(credential_id);
CREATE INDEX idx_passkeys_user_id ON public.passkeys(user_id);
