-- Create password_resets table for password recovery flow
CREATE TABLE IF NOT EXISTS password_resets (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id INTEGER REFERENCES person_details(user_id),
  token TEXT NOT NULL UNIQUE,
  expires_at TIMESTAMPTZ NOT NULL,
  used_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Create indexes for faster lookups
CREATE INDEX IF NOT EXISTS idx_password_resets_token ON password_resets(token);
CREATE INDEX IF NOT EXISTS idx_password_resets_expires ON password_resets(expires_at);
CREATE INDEX IF NOT EXISTS idx_password_resets_user ON password_resets(user_id);

-- Add RLS policies
ALTER TABLE password_resets ENABLE ROW LEVEL SECURITY;

-- Allow service role full access
CREATE POLICY "Service role can manage password_resets"
  ON password_resets
  FOR ALL
  USING (true)
  WITH CHECK (true);

-- Clean up expired tokens (optional: run periodically)
-- DELETE FROM password_resets WHERE expires_at < NOW() AND used_at IS NULL;
