-- Add ip column to challenges (idempotent)
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'public' AND table_name = 'challenges' AND column_name = 'ip'
  ) THEN
    ALTER TABLE challenges ADD COLUMN ip TEXT;
  END IF;
END $$;

-- User login history (ip, created_at per user)
CREATE TABLE IF NOT EXISTS user_logins (
  id SERIAL PRIMARY KEY,
  public_key TEXT NOT NULL REFERENCES users(public_key) ON DELETE CASCADE,
  ip TEXT NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_user_logins_public_key ON user_logins(public_key);
CREATE INDEX IF NOT EXISTS idx_user_logins_created_at ON user_logins(created_at);
